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 0x7f668261e090>
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.336408 -0.591179 1.669736 -2.376495
2013-01-02 -0.265843 -1.364178 0.195668 -0.111914
2013-01-03 0.588897 1.824482 0.803117 -0.759495
2013-01-04 0.736645 0.612289 0.242060 -1.125579
2013-01-05 -1.997406 1.471966 -1.483082 -0.912298
2013-01-06 -0.520070 -0.154318 1.329614 0.997960
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.336408 -0.591179 1.669736 -2.376495
2013-01-02 -0.265843 -1.364178 0.195668 -0.111914
2013-01-03 0.588897 1.824482 0.803117 -0.759495
2013-01-04 0.736645 0.612289 0.242060 -1.125579
2013-01-05 -1.997406 1.471966 -1.483082 -0.912298
In [15]: df.tail(3).execute()
Out[15]:
A B C D
2013-01-04 0.736645 0.612289 0.242060 -1.125579
2013-01-05 -1.997406 1.471966 -1.483082 -0.912298
2013-01-06 -0.520070 -0.154318 1.329614 0.997960
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.33640776, -0.59117852, 1.66973576, -2.37649455],
[-0.26584289, -1.3641777 , 0.19566803, -0.11191423],
[ 0.5888971 , 1.82448223, 0.80311717, -0.75949523],
[ 0.73664506, 0.61228856, 0.24206002, -1.12557932],
[-1.99740639, 1.47196586, -1.48308238, -0.91229808],
[-0.52006996, -0.15431756, 1.32961439, 0.99795983]])
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.186895 0.299844 0.459519 -0.714637
std 1.012306 1.230054 1.116276 1.119642
min -1.997406 -1.364178 -1.483082 -2.376495
25% -0.456513 -0.481963 0.207266 -1.072259
50% 0.035282 0.228986 0.522589 -0.835897
75% 0.525775 1.257047 1.197990 -0.273809
max 0.736645 1.824482 1.669736 0.997960
Sorting by an axis:
In [21]: df.sort_index(axis=1, ascending=False).execute()
Out[21]:
D C B A
2013-01-01 -2.376495 1.669736 -0.591179 0.336408
2013-01-02 -0.111914 0.195668 -1.364178 -0.265843
2013-01-03 -0.759495 0.803117 1.824482 0.588897
2013-01-04 -1.125579 0.242060 0.612289 0.736645
2013-01-05 -0.912298 -1.483082 1.471966 -1.997406
2013-01-06 0.997960 1.329614 -0.154318 -0.520070
Sorting by values:
In [22]: df.sort_values(by='B').execute()
Out[22]:
A B C D
2013-01-02 -0.265843 -1.364178 0.195668 -0.111914
2013-01-01 0.336408 -0.591179 1.669736 -2.376495
2013-01-06 -0.520070 -0.154318 1.329614 0.997960
2013-01-04 0.736645 0.612289 0.242060 -1.125579
2013-01-05 -1.997406 1.471966 -1.483082 -0.912298
2013-01-03 0.588897 1.824482 0.803117 -0.759495
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.336408
2013-01-02 -0.265843
2013-01-03 0.588897
2013-01-04 0.736645
2013-01-05 -1.997406
2013-01-06 -0.520070
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.336408 -0.591179 1.669736 -2.376495
2013-01-02 -0.265843 -1.364178 0.195668 -0.111914
2013-01-03 0.588897 1.824482 0.803117 -0.759495
In [25]: df['20130102':'20130104'].execute()
Out[25]:
A B C D
2013-01-02 -0.265843 -1.364178 0.195668 -0.111914
2013-01-03 0.588897 1.824482 0.803117 -0.759495
2013-01-04 0.736645 0.612289 0.242060 -1.125579
Selection by label¶
For getting a cross section using a label:
In [26]: df.loc['20130101'].execute()
Out[26]:
A 0.336408
B -0.591179
C 1.669736
D -2.376495
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.336408 -0.591179
2013-01-02 -0.265843 -1.364178
2013-01-03 0.588897 1.824482
2013-01-04 0.736645 0.612289
2013-01-05 -1.997406 1.471966
2013-01-06 -0.520070 -0.154318
Showing label slicing, both endpoints are included:
In [28]: df.loc['20130102':'20130104', ['A', 'B']].execute()
Out[28]:
A B
2013-01-02 -0.265843 -1.364178
2013-01-03 0.588897 1.824482
2013-01-04 0.736645 0.612289
Reduction in the dimensions of the returned object:
In [29]: df.loc['20130102', ['A', 'B']].execute()
Out[29]:
A -0.265843
B -1.364178
Name: 2013-01-02 00:00:00, dtype: float64
For getting a scalar value:
In [30]: df.loc['20130101', 'A'].execute()
Out[30]: 0.3364077559427176
For getting fast access to a scalar (equivalent to the prior method):
In [31]: df.at['20130101', 'A'].execute()
Out[31]: 0.3364077559427176
Selection by position¶
Select via the position of the passed integers:
In [32]: df.iloc[3].execute()
Out[32]:
A 0.736645
B 0.612289
C 0.242060
D -1.125579
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 0.736645 0.612289
2013-01-05 -1.997406 1.471966
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.265843 0.195668
2013-01-03 0.588897 0.803117
2013-01-05 -1.997406 -1.483082
For slicing rows explicitly:
In [35]: df.iloc[1:3, :].execute()
Out[35]:
A B C D
2013-01-02 -0.265843 -1.364178 0.195668 -0.111914
2013-01-03 0.588897 1.824482 0.803117 -0.759495
For slicing columns explicitly:
In [36]: df.iloc[:, 1:3].execute()
Out[36]:
B C
2013-01-01 -0.591179 1.669736
2013-01-02 -1.364178 0.195668
2013-01-03 1.824482 0.803117
2013-01-04 0.612289 0.242060
2013-01-05 1.471966 -1.483082
2013-01-06 -0.154318 1.329614
For getting a value explicitly:
In [37]: df.iloc[1, 1].execute()
Out[37]: -1.3641777004270788
For getting fast access to a scalar (equivalent to the prior method):
In [38]: df.iat[1, 1].execute()
Out[38]: -1.3641777004270788
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-01 0.336408 -0.591179 1.669736 -2.376495
2013-01-03 0.588897 1.824482 0.803117 -0.759495
2013-01-04 0.736645 0.612289 0.242060 -1.125579
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 0.336408 NaN 1.669736 NaN
2013-01-02 NaN NaN 0.195668 NaN
2013-01-03 0.588897 1.824482 0.803117 NaN
2013-01-04 0.736645 0.612289 0.242060 NaN
2013-01-05 NaN 1.471966 NaN NaN
2013-01-06 NaN NaN 1.329614 0.99796
Operations¶
Stats¶
Operations in general exclude missing data.
Performing a descriptive statistic:
In [41]: df.mean().execute()
Out[41]:
A -0.186895
B 0.299844
C 0.459519
D -0.714637
dtype: float64
Same operation on the other axis:
In [42]: df.mean(1).execute()
Out[42]:
2013-01-01 -0.240382
2013-01-02 -0.386567
2013-01-03 0.614250
2013-01-04 0.116354
2013-01-05 -0.730205
2013-01-06 0.413297
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.411103 0.824482 -0.196883 -1.759495
2013-01-04 -2.263355 -2.387711 -2.757940 -4.125579
2013-01-05 -6.997406 -3.528034 -6.483082 -5.912298
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.734051
B 3.188660
C 3.152818
D 3.374454
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.569280 -1.019281 -0.051854 1.074545
1 0.528347 -0.402079 -1.007305 -0.207577
2 -0.918585 1.258735 -0.424030 1.458511
3 0.503231 0.082010 2.110152 -0.688240
4 -0.584119 0.145481 -0.887561 -0.192745
5 -1.463052 -1.944418 -1.349207 -0.046024
6 1.992561 0.951382 1.058893 1.171185
7 1.991618 0.045671 -0.003086 -0.728965
8 0.280105 -0.372272 0.977936 -1.490267
9 -0.360202 0.762831 0.030429 0.448750
# 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.569280 -1.019281 -0.051854 1.074545
1 0.528347 -0.402079 -1.007305 -0.207577
2 -0.918585 1.258735 -0.424030 1.458511
3 0.503231 0.082010 2.110152 -0.688240
4 -0.584119 0.145481 -0.887561 -0.192745
5 -1.463052 -1.944418 -1.349207 -0.046024
6 1.992561 0.951382 1.058893 1.171185
7 1.991618 0.045671 -0.003086 -0.728965
8 0.280105 -0.372272 0.977936 -1.490267
9 -0.360202 0.762831 0.030429 0.448750
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.151781 -0.695650
1 bar one -0.457911 1.668589
2 foo two 1.218667 0.626749
3 bar three -1.018252 0.609330
4 foo two -1.239349 1.233556
5 bar two 0.474177 1.136801
6 foo one -1.388867 0.349432
7 foo three 0.032801 1.307410
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.001986 3.414720
foo -1.224967 2.821499
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.457911 1.668589
three -1.018252 0.609330
two 0.474177 1.136801
foo one -1.237086 -0.346217
three 0.032801 1.307410
two -0.020682 1.860306
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 0x7f6686e6cf90>
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 1.654730 0.034190 1.592940 0.114646
1 2000-01-02 0.182614 0.097960 2.175979 -1.989463
2 2000-01-03 -0.832394 1.003577 1.818398 -2.193297
3 2000-01-04 -1.297659 0.608756 2.489221 -1.960197
4 2000-01-05 0.181572 2.757184 2.221153 -0.768151
.. ... ... ... ... ...
995 2002-09-22 -53.725808 14.149430 52.744021 -63.883534
996 2002-09-23 -53.912809 13.219599 53.681973 -63.495749
997 2002-09-24 -52.332776 14.164051 56.389689 -63.304450
998 2002-09-25 -51.487259 14.324083 57.955803 -63.418465
999 2002-09-26 -52.553009 13.501106 56.709544 -60.787730
[1000 rows x 5 columns]