10 minutes to Mars DataFrame¶
This is a short introduction to Mars DataFrame which is originated from 10 minutes to pandas.
Customarily, we import as follows:
In [1]: import mars
In [2]: import mars.tensor as mt
In [3]: import mars.dataframe as md
Now create a new default session.
In [4]: mars.new_session()
Out[4]: <mars.deploy.oscar.session.SyncSession at 0x7fa772e2ce50>
Object creation¶
Creating a Series
by passing a list of values, letting it create
a default integer index:
In [5]: s = md.Series([1, 3, 5, mt.nan, 6, 8])
In [6]: s.execute()
Out[6]:
0 1.0
1 3.0
2 5.0
3 NaN
4 6.0
5 8.0
dtype: float64
Creating a DataFrame
by passing a Mars tensor, with a datetime index
and labeled columns:
In [7]: dates = md.date_range('20130101', periods=6)
In [8]: dates.execute()
Out[8]:
DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',
'2013-01-05', '2013-01-06'],
dtype='datetime64[ns]', freq='D')
In [9]: df = md.DataFrame(mt.random.randn(6, 4), index=dates, columns=list('ABCD'))
In [10]: df.execute()
Out[10]:
A B C D
2013-01-01 -0.732706 0.515466 -0.349193 -0.636223
2013-01-02 -0.157328 0.155724 2.140505 0.450986
2013-01-03 0.657246 -0.867057 -0.089616 -0.002617
2013-01-04 -1.551333 0.141346 0.714340 -1.470825
2013-01-05 -0.326916 0.348456 0.913137 -0.729413
2013-01-06 -1.431079 0.536241 -1.110880 0.215855
Creating a DataFrame
by passing a dict of objects that can be converted to series-like.
In [11]: df2 = md.DataFrame({'A': 1.,
....: 'B': md.Timestamp('20130102'),
....: 'C': md.Series(1, index=list(range(4)), dtype='float32'),
....: 'D': mt.array([3] * 4, dtype='int32'),
....: 'E': 'foo'})
....:
In [12]: df2.execute()
Out[12]:
A B C D E
0 1.0 2013-01-02 1.0 3 foo
1 1.0 2013-01-02 1.0 3 foo
2 1.0 2013-01-02 1.0 3 foo
3 1.0 2013-01-02 1.0 3 foo
The columns of the resulting DataFrame
have different dtypes.
In [13]: df2.dtypes
Out[13]:
A float64
B datetime64[ns]
C float32
D int32
E object
dtype: object
Viewing data¶
Here is how to view the top and bottom rows of the frame:
In [14]: df.head().execute()
Out[14]:
A B C D
2013-01-01 -0.732706 0.515466 -0.349193 -0.636223
2013-01-02 -0.157328 0.155724 2.140505 0.450986
2013-01-03 0.657246 -0.867057 -0.089616 -0.002617
2013-01-04 -1.551333 0.141346 0.714340 -1.470825
2013-01-05 -0.326916 0.348456 0.913137 -0.729413
In [15]: df.tail(3).execute()
Out[15]:
A B C D
2013-01-04 -1.551333 0.141346 0.714340 -1.470825
2013-01-05 -0.326916 0.348456 0.913137 -0.729413
2013-01-06 -1.431079 0.536241 -1.110880 0.215855
Display the index, columns:
In [16]: df.index.execute()
Out[16]:
DatetimeIndex(['2013-01-01', '2013-01-02', '2013-01-03', '2013-01-04',
'2013-01-05', '2013-01-06'],
dtype='datetime64[ns]', freq='D')
In [17]: df.columns.execute()
Out[17]: Index(['A', 'B', 'C', 'D'], dtype='object')
DataFrame.to_tensor()
gives a Mars tensor representation of the underlying data.
Note that this can be an expensive operation when your DataFrame
has
columns with different data types, which comes down to a fundamental difference
between DataFrame and tensor: tensors have one dtype for the entire tensor,
while DataFrames have one dtype per column. When you call
DataFrame.to_tensor()
, Mars DataFrame will find the tensor dtype that can hold all
of the dtypes in the DataFrame. This may end up being object
, which requires
casting every value to a Python object.
For df
, our DataFrame
of all floating-point values,
DataFrame.to_tensor()
is fast and doesn’t require copying data.
In [18]: df.to_tensor().execute()
Out[18]:
array([[-0.73270575, 0.51546566, -0.349193 , -0.63622333],
[-0.15732779, 0.15572426, 2.1405048 , 0.45098589],
[ 0.65724622, -0.86705737, -0.08961628, -0.00261658],
[-1.55133326, 0.14134596, 0.71433985, -1.47082512],
[-0.32691554, 0.34845572, 0.91313674, -0.72941259],
[-1.4310785 , 0.53624113, -1.11087961, 0.21585544]])
For df2
, the DataFrame
with multiple dtypes,
DataFrame.to_tensor()
is relatively expensive.
In [19]: df2.to_tensor().execute()
Out[19]:
array([[1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'foo'],
[1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'foo'],
[1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'foo'],
[1.0, Timestamp('2013-01-02 00:00:00'), 1.0, 3, 'foo']],
dtype=object)
Note
DataFrame.to_tensor()
does not include the index or column
labels in the output.
describe()
shows a quick statistic summary of your data:
In [20]: df.describe().execute()
Out[20]:
A B C D
count 6.000000 6.000000 6.000000 6.000000
mean -0.590352 0.138363 0.369715 -0.362039
std 0.832344 0.520737 1.137519 0.716059
min -1.551333 -0.867057 -1.110880 -1.470825
25% -1.256485 0.144941 -0.284299 -0.706115
50% -0.529811 0.252090 0.312362 -0.319420
75% -0.199725 0.473713 0.863438 0.161237
max 0.657246 0.536241 2.140505 0.450986
Sorting by an axis:
In [21]: df.sort_index(axis=1, ascending=False).execute()
Out[21]:
D C B A
2013-01-01 -0.636223 -0.349193 0.515466 -0.732706
2013-01-02 0.450986 2.140505 0.155724 -0.157328
2013-01-03 -0.002617 -0.089616 -0.867057 0.657246
2013-01-04 -1.470825 0.714340 0.141346 -1.551333
2013-01-05 -0.729413 0.913137 0.348456 -0.326916
2013-01-06 0.215855 -1.110880 0.536241 -1.431079
Sorting by values:
In [22]: df.sort_values(by='B').execute()
Out[22]:
A B C D
2013-01-03 0.657246 -0.867057 -0.089616 -0.002617
2013-01-04 -1.551333 0.141346 0.714340 -1.470825
2013-01-02 -0.157328 0.155724 2.140505 0.450986
2013-01-05 -0.326916 0.348456 0.913137 -0.729413
2013-01-01 -0.732706 0.515466 -0.349193 -0.636223
2013-01-06 -1.431079 0.536241 -1.110880 0.215855
Selection¶
Note
While standard Python / Numpy expressions for selecting and setting are
intuitive and come in handy for interactive work, for production code, we
recommend the optimized DataFrame data access methods, .at
, .iat
,
.loc
and .iloc
.
Getting¶
Selecting a single column, which yields a Series
,
equivalent to df.A
:
In [23]: df['A'].execute()
Out[23]:
2013-01-01 -0.732706
2013-01-02 -0.157328
2013-01-03 0.657246
2013-01-04 -1.551333
2013-01-05 -0.326916
2013-01-06 -1.431079
Freq: D, Name: A, dtype: float64
Selecting via []
, which slices the rows.
In [24]: df[0:3].execute()
Out[24]:
A B C D
2013-01-01 -0.732706 0.515466 -0.349193 -0.636223
2013-01-02 -0.157328 0.155724 2.140505 0.450986
2013-01-03 0.657246 -0.867057 -0.089616 -0.002617
In [25]: df['20130102':'20130104'].execute()
Out[25]:
A B C D
2013-01-02 -0.157328 0.155724 2.140505 0.450986
2013-01-03 0.657246 -0.867057 -0.089616 -0.002617
2013-01-04 -1.551333 0.141346 0.714340 -1.470825
Selection by label¶
For getting a cross section using a label:
In [26]: df.loc['20130101'].execute()
Out[26]:
A -0.732706
B 0.515466
C -0.349193
D -0.636223
Name: 2013-01-01 00:00:00, dtype: float64
Selecting on a multi-axis by label:
In [27]: df.loc[:, ['A', 'B']].execute()
Out[27]:
A B
2013-01-01 -0.732706 0.515466
2013-01-02 -0.157328 0.155724
2013-01-03 0.657246 -0.867057
2013-01-04 -1.551333 0.141346
2013-01-05 -0.326916 0.348456
2013-01-06 -1.431079 0.536241
Showing label slicing, both endpoints are included:
In [28]: df.loc['20130102':'20130104', ['A', 'B']].execute()
Out[28]:
A B
2013-01-02 -0.157328 0.155724
2013-01-03 0.657246 -0.867057
2013-01-04 -1.551333 0.141346
Reduction in the dimensions of the returned object:
In [29]: df.loc['20130102', ['A', 'B']].execute()
Out[29]:
A -0.157328
B 0.155724
Name: 2013-01-02 00:00:00, dtype: float64
For getting a scalar value:
In [30]: df.loc['20130101', 'A'].execute()
Out[30]: -0.7327057460580094
For getting fast access to a scalar (equivalent to the prior method):
In [31]: df.at['20130101', 'A'].execute()
Out[31]: -0.7327057460580094
Selection by position¶
Select via the position of the passed integers:
In [32]: df.iloc[3].execute()
Out[32]:
A -1.551333
B 0.141346
C 0.714340
D -1.470825
Name: 2013-01-04 00:00:00, dtype: float64
By integer slices, acting similar to numpy/python:
In [33]: df.iloc[3:5, 0:2].execute()
Out[33]:
A B
2013-01-04 -1.551333 0.141346
2013-01-05 -0.326916 0.348456
By lists of integer position locations, similar to the numpy/python style:
In [34]: df.iloc[[1, 2, 4], [0, 2]].execute()
Out[34]:
A C
2013-01-02 -0.157328 2.140505
2013-01-03 0.657246 -0.089616
2013-01-05 -0.326916 0.913137
For slicing rows explicitly:
In [35]: df.iloc[1:3, :].execute()
Out[35]:
A B C D
2013-01-02 -0.157328 0.155724 2.140505 0.450986
2013-01-03 0.657246 -0.867057 -0.089616 -0.002617
For slicing columns explicitly:
In [36]: df.iloc[:, 1:3].execute()
Out[36]:
B C
2013-01-01 0.515466 -0.349193
2013-01-02 0.155724 2.140505
2013-01-03 -0.867057 -0.089616
2013-01-04 0.141346 0.714340
2013-01-05 0.348456 0.913137
2013-01-06 0.536241 -1.110880
For getting a value explicitly:
In [37]: df.iloc[1, 1].execute()
Out[37]: 0.15572426486304516
For getting fast access to a scalar (equivalent to the prior method):
In [38]: df.iat[1, 1].execute()
Out[38]: 0.15572426486304516
Boolean indexing¶
Using a single column’s values to select data.
In [39]: df[df['A'] > 0].execute()
Out[39]:
A B C D
2013-01-03 0.657246 -0.867057 -0.089616 -0.002617
Selecting values from a DataFrame where a boolean condition is met.
In [40]: df[df > 0].execute()
Out[40]:
A B C D
2013-01-01 NaN 0.515466 NaN NaN
2013-01-02 NaN 0.155724 2.140505 0.450986
2013-01-03 0.657246 NaN NaN NaN
2013-01-04 NaN 0.141346 0.714340 NaN
2013-01-05 NaN 0.348456 0.913137 NaN
2013-01-06 NaN 0.536241 NaN 0.215855
Operations¶
Stats¶
Operations in general exclude missing data.
Performing a descriptive statistic:
In [41]: df.mean().execute()
Out[41]:
A -0.590352
B 0.138363
C 0.369715
D -0.362039
dtype: float64
Same operation on the other axis:
In [42]: df.mean(1).execute()
Out[42]:
2013-01-01 -0.300664
2013-01-02 0.647472
2013-01-03 -0.075511
2013-01-04 -0.541618
2013-01-05 0.051316
2013-01-06 -0.447465
Freq: D, dtype: float64
Operating with objects that have different dimensionality and need alignment. In addition, Mars DataFrame automatically broadcasts along the specified dimension.
In [43]: s = md.Series([1, 3, 5, mt.nan, 6, 8], index=dates).shift(2)
In [44]: s.execute()
Out[44]:
2013-01-01 NaN
2013-01-02 NaN
2013-01-03 1.0
2013-01-04 3.0
2013-01-05 5.0
2013-01-06 NaN
Freq: D, dtype: float64
In [45]: df.sub(s, axis='index').execute()
Out[45]:
A B C D
2013-01-01 NaN NaN NaN NaN
2013-01-02 NaN NaN NaN NaN
2013-01-03 -0.342754 -1.867057 -1.089616 -1.002617
2013-01-04 -4.551333 -2.858654 -2.285660 -4.470825
2013-01-05 -5.326916 -4.651544 -4.086863 -5.729413
2013-01-06 NaN NaN NaN NaN
Apply¶
Applying functions to the data:
In [46]: df.apply(lambda x: x.max() - x.min()).execute()
Out[46]:
A 2.208579
B 1.403298
C 3.251384
D 1.921811
dtype: float64
String Methods¶
Series is equipped with a set of string processing methods in the str attribute that make it easy to operate on each element of the array, as in the code snippet below. Note that pattern-matching in str generally uses regular expressions by default (and in some cases always uses them). See more at Vectorized String Methods.
In [47]: s = md.Series(['A', 'B', 'C', 'Aaba', 'Baca', mt.nan, 'CABA', 'dog', 'cat'])
In [48]: s.str.lower().execute()
Out[48]:
0 a
1 b
2 c
3 aaba
4 baca
5 NaN
6 caba
7 dog
8 cat
dtype: object
Merge¶
Concat¶
Mars DataFrame provides various facilities for easily combining together Series and DataFrame objects with various kinds of set logic for the indexes and relational algebra functionality in the case of join / merge-type operations.
Concatenating DataFrame objects together with concat()
:
In [49]: df = md.DataFrame(mt.random.randn(10, 4))
In [50]: df.execute()
Out[50]:
0 1 2 3
0 0.620875 -0.008506 0.058023 -0.935586
1 1.458811 -0.041924 -0.265783 1.054654
2 0.197659 -0.345677 -0.574321 0.216816
3 -0.938168 0.652873 0.560777 -0.586455
4 -0.267727 -0.178207 -2.071679 0.492330
5 1.720697 -1.138567 -1.253732 -0.201089
6 -0.189984 -0.127665 0.514545 -0.136464
7 -1.982466 -0.856163 -0.088314 0.756383
8 0.332301 0.665709 1.323137 -1.877691
9 -0.047860 -0.330600 -1.008798 -0.658088
# break it into pieces
In [51]: pieces = [df[:3], df[3:7], df[7:]]
In [52]: md.concat(pieces).execute()
Out[52]:
0 1 2 3
0 0.620875 -0.008506 0.058023 -0.935586
1 1.458811 -0.041924 -0.265783 1.054654
2 0.197659 -0.345677 -0.574321 0.216816
3 -0.938168 0.652873 0.560777 -0.586455
4 -0.267727 -0.178207 -2.071679 0.492330
5 1.720697 -1.138567 -1.253732 -0.201089
6 -0.189984 -0.127665 0.514545 -0.136464
7 -1.982466 -0.856163 -0.088314 0.756383
8 0.332301 0.665709 1.323137 -1.877691
9 -0.047860 -0.330600 -1.008798 -0.658088
Join¶
SQL style merges. See the Database style joining section.
In [53]: left = md.DataFrame({'key': ['foo', 'foo'], 'lval': [1, 2]})
In [54]: right = md.DataFrame({'key': ['foo', 'foo'], 'rval': [4, 5]})
In [55]: left.execute()
Out[55]:
key lval
0 foo 1
1 foo 2
In [56]: right.execute()
Out[56]:
key rval
0 foo 4
1 foo 5
In [57]: md.merge(left, right, on='key').execute()
Out[57]:
key lval rval
0 foo 1 4
1 foo 1 5
2 foo 2 4
3 foo 2 5
Another example that can be given is:
In [58]: left = md.DataFrame({'key': ['foo', 'bar'], 'lval': [1, 2]})
In [59]: right = md.DataFrame({'key': ['foo', 'bar'], 'rval': [4, 5]})
In [60]: left.execute()
Out[60]:
key lval
0 foo 1
1 bar 2
In [61]: right.execute()
Out[61]:
key rval
0 foo 4
1 bar 5
In [62]: md.merge(left, right, on='key').execute()
Out[62]:
key lval rval
0 foo 1 4
1 bar 2 5
Grouping¶
By “group by” we are referring to a process involving one or more of the following steps:
Splitting the data into groups based on some criteria
Applying a function to each group independently
Combining the results into a data structure
In [63]: df = md.DataFrame({'A': ['foo', 'bar', 'foo', 'bar',
....: 'foo', 'bar', 'foo', 'foo'],
....: 'B': ['one', 'one', 'two', 'three',
....: 'two', 'two', 'one', 'three'],
....: 'C': mt.random.randn(8),
....: 'D': mt.random.randn(8)})
....:
In [64]: df.execute()
Out[64]:
A B C D
0 foo one -0.380289 0.232569
1 bar one 0.240010 0.010508
2 foo two 0.996394 -0.969489
3 bar three -0.429355 -0.541797
4 foo two 1.183736 -0.727124
5 bar two -1.285523 -0.860006
6 foo one 0.310101 -0.744572
7 foo three 1.864274 1.858599
Grouping and then applying the sum()
function to the resulting
groups.
In [65]: df.groupby('A').sum().execute()
Out[65]:
C D
A
bar -1.474867 -1.391296
foo 3.974216 -0.350017
Grouping by multiple columns forms a hierarchical index, and again we can apply the sum function.
In [66]: df.groupby(['A', 'B']).sum().execute()
Out[66]:
C D
A B
bar one 0.240010 0.010508
three -0.429355 -0.541797
two -1.285523 -0.860006
foo one -0.070188 -0.512003
three 1.864274 1.858599
two 2.180130 -1.696613
Plotting¶
We use the standard convention for referencing the matplotlib API:
In [67]: import matplotlib.pyplot as plt
In [68]: plt.close('all')
In [69]: ts = md.Series(mt.random.randn(1000),
....: index=md.date_range('1/1/2000', periods=1000))
....:
In [70]: ts = ts.cumsum()
In [71]: ts.plot()
Out[71]: <AxesSubplot:>
On a DataFrame, the plot()
method is a convenience to plot all
of the columns with labels:
In [72]: df = md.DataFrame(mt.random.randn(1000, 4), index=ts.index,
....: columns=['A', 'B', 'C', 'D'])
....:
In [73]: df = df.cumsum()
In [74]: plt.figure()
Out[74]: <Figure size 640x480 with 0 Axes>
In [75]: df.plot()
Out[75]: <AxesSubplot:>
In [76]: plt.legend(loc='best')
Out[76]: <matplotlib.legend.Legend at 0x7fa7738bfb10>
Getting data in/out¶
CSV¶
In [77]: df.to_csv('foo.csv').execute()
Out[77]:
Empty DataFrame
Columns: []
Index: []
In [78]: md.read_csv('foo.csv').execute()
Out[78]:
Unnamed: 0 A B C D
0 2000-01-01 -0.300163 0.337617 1.036481 -1.876343
1 2000-01-02 0.992352 0.976087 1.129894 -1.453266
2 2000-01-03 0.726812 0.682792 2.107158 -2.634286
3 2000-01-04 2.276781 2.310293 1.329027 -2.632257
4 2000-01-05 0.896290 3.045890 1.913971 -2.578021
.. ... ... ... ... ...
995 2002-09-22 0.344114 6.261014 -19.146423 -48.677086
996 2002-09-23 0.658127 6.315118 -18.974569 -48.330503
997 2002-09-24 1.271757 7.100011 -17.737045 -48.099895
998 2002-09-25 1.174010 5.785241 -17.706135 -48.490238
999 2002-09-26 1.577179 6.911654 -15.867038 -46.289565
[1000 rows x 5 columns]