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 0x7fc32da65710>
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 -1.154713 1.126999 -0.121116 0.008886
2013-01-02 2.004474 0.625649 -0.072003 -0.244366
2013-01-03 -0.412276 -0.360237 0.186695 0.554216
2013-01-04 -2.901208 0.215376 -1.698960 1.459582
2013-01-05 0.738152 0.339431 1.192081 0.970703
2013-01-06 -0.853461 -0.799830 0.320724 -0.995249
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 -1.154713 1.126999 -0.121116 0.008886
2013-01-02 2.004474 0.625649 -0.072003 -0.244366
2013-01-03 -0.412276 -0.360237 0.186695 0.554216
2013-01-04 -2.901208 0.215376 -1.698960 1.459582
2013-01-05 0.738152 0.339431 1.192081 0.970703
In [15]: df.tail(3).execute()
Out[15]:
A B C D
2013-01-04 -2.901208 0.215376 -1.698960 1.459582
2013-01-05 0.738152 0.339431 1.192081 0.970703
2013-01-06 -0.853461 -0.799830 0.320724 -0.995249
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([[-1.15471313, 1.12699877, -0.12111647, 0.00888647],
[ 2.00447359, 0.6256494 , -0.07200269, -0.24436604],
[-0.41227607, -0.36023747, 0.18669517, 0.55421638],
[-2.90120832, 0.21537632, -1.69896028, 1.45958154],
[ 0.73815229, 0.33943131, 1.19208077, 0.97070281],
[-0.85346062, -0.79983024, 0.32072424, -0.99524853]])
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.429839 0.191231 -0.032097 0.292295
std 1.679461 0.688948 0.944343 0.885154
min -2.901208 -0.799830 -1.698960 -0.995249
25% -1.079400 -0.216334 -0.108838 -0.181053
50% -0.632868 0.277404 0.057346 0.281551
75% 0.450545 0.554095 0.287217 0.866581
max 2.004474 1.126999 1.192081 1.459582
Sorting by an axis:
In [21]: df.sort_index(axis=1, ascending=False).execute()
Out[21]:
D C B A
2013-01-01 0.008886 -0.121116 1.126999 -1.154713
2013-01-02 -0.244366 -0.072003 0.625649 2.004474
2013-01-03 0.554216 0.186695 -0.360237 -0.412276
2013-01-04 1.459582 -1.698960 0.215376 -2.901208
2013-01-05 0.970703 1.192081 0.339431 0.738152
2013-01-06 -0.995249 0.320724 -0.799830 -0.853461
Sorting by values:
In [22]: df.sort_values(by='B').execute()
Out[22]:
A B C D
2013-01-06 -0.853461 -0.799830 0.320724 -0.995249
2013-01-03 -0.412276 -0.360237 0.186695 0.554216
2013-01-04 -2.901208 0.215376 -1.698960 1.459582
2013-01-05 0.738152 0.339431 1.192081 0.970703
2013-01-02 2.004474 0.625649 -0.072003 -0.244366
2013-01-01 -1.154713 1.126999 -0.121116 0.008886
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 -1.154713
2013-01-02 2.004474
2013-01-03 -0.412276
2013-01-04 -2.901208
2013-01-05 0.738152
2013-01-06 -0.853461
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 -1.154713 1.126999 -0.121116 0.008886
2013-01-02 2.004474 0.625649 -0.072003 -0.244366
2013-01-03 -0.412276 -0.360237 0.186695 0.554216
In [25]: df['20130102':'20130104'].execute()
Out[25]:
A B C D
2013-01-02 2.004474 0.625649 -0.072003 -0.244366
2013-01-03 -0.412276 -0.360237 0.186695 0.554216
2013-01-04 -2.901208 0.215376 -1.698960 1.459582
Selection by label#
For getting a cross section using a label:
In [26]: df.loc['20130101'].execute()
Out[26]:
A -1.154713
B 1.126999
C -0.121116
D 0.008886
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 -1.154713 1.126999
2013-01-02 2.004474 0.625649
2013-01-03 -0.412276 -0.360237
2013-01-04 -2.901208 0.215376
2013-01-05 0.738152 0.339431
2013-01-06 -0.853461 -0.799830
Showing label slicing, both endpoints are included:
In [28]: df.loc['20130102':'20130104', ['A', 'B']].execute()
Out[28]:
A B
2013-01-02 2.004474 0.625649
2013-01-03 -0.412276 -0.360237
2013-01-04 -2.901208 0.215376
Reduction in the dimensions of the returned object:
In [29]: df.loc['20130102', ['A', 'B']].execute()
Out[29]:
A 2.004474
B 0.625649
Name: 2013-01-02 00:00:00, dtype: float64
For getting a scalar value:
In [30]: df.loc['20130101', 'A'].execute()
Out[30]: -1.1547131314038468
For getting fast access to a scalar (equivalent to the prior method):
In [31]: df.at['20130101', 'A'].execute()
Out[31]: -1.1547131314038468
Selection by position#
Select via the position of the passed integers:
In [32]: df.iloc[3].execute()
Out[32]:
A -2.901208
B 0.215376
C -1.698960
D 1.459582
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 -2.901208 0.215376
2013-01-05 0.738152 0.339431
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 2.004474 -0.072003
2013-01-03 -0.412276 0.186695
2013-01-05 0.738152 1.192081
For slicing rows explicitly:
In [35]: df.iloc[1:3, :].execute()
Out[35]:
A B C D
2013-01-02 2.004474 0.625649 -0.072003 -0.244366
2013-01-03 -0.412276 -0.360237 0.186695 0.554216
For slicing columns explicitly:
In [36]: df.iloc[:, 1:3].execute()
Out[36]:
B C
2013-01-01 1.126999 -0.121116
2013-01-02 0.625649 -0.072003
2013-01-03 -0.360237 0.186695
2013-01-04 0.215376 -1.698960
2013-01-05 0.339431 1.192081
2013-01-06 -0.799830 0.320724
For getting a value explicitly:
In [37]: df.iloc[1, 1].execute()
Out[37]: 0.6256494008687327
For getting fast access to a scalar (equivalent to the prior method):
In [38]: df.iat[1, 1].execute()
Out[38]: 0.6256494008687327
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-02 2.004474 0.625649 -0.072003 -0.244366
2013-01-05 0.738152 0.339431 1.192081 0.970703
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 1.126999 NaN 0.008886
2013-01-02 2.004474 0.625649 NaN NaN
2013-01-03 NaN NaN 0.186695 0.554216
2013-01-04 NaN 0.215376 NaN 1.459582
2013-01-05 0.738152 0.339431 1.192081 0.970703
2013-01-06 NaN NaN 0.320724 NaN
Operations#
Stats#
Operations in general exclude missing data.
Performing a descriptive statistic:
In [41]: df.mean().execute()
Out[41]:
A -0.429839
B 0.191231
C -0.032097
D 0.292295
dtype: float64
Same operation on the other axis:
In [42]: df.mean(1).execute()
Out[42]:
2013-01-01 -0.034986
2013-01-02 0.578439
2013-01-03 -0.007900
2013-01-04 -0.731303
2013-01-05 0.810092
2013-01-06 -0.581954
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 -1.412276 -1.360237 -0.813305 -0.445784
2013-01-04 -5.901208 -2.784624 -4.698960 -1.540418
2013-01-05 -4.261848 -4.660569 -3.807919 -4.029297
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 4.905682
B 1.926829
C 2.891041
D 2.454830
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.953826 1.545058 0.175901 0.262698
1 0.715620 1.370578 -0.737252 -1.272021
2 0.536494 1.190122 1.342157 -0.626725
3 0.640357 -0.984611 -0.717763 -1.598003
4 0.930090 0.989741 -1.535904 1.381829
5 -0.229707 1.417013 -0.236877 0.344851
6 0.325114 -0.368508 1.013749 0.069613
7 2.055862 -1.085238 0.276277 -0.081811
8 -1.876217 -1.058380 -0.409820 -1.029904
9 0.386319 -1.906937 0.075222 0.120449
# 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.953826 1.545058 0.175901 0.262698
1 0.715620 1.370578 -0.737252 -1.272021
2 0.536494 1.190122 1.342157 -0.626725
3 0.640357 -0.984611 -0.717763 -1.598003
4 0.930090 0.989741 -1.535904 1.381829
5 -0.229707 1.417013 -0.236877 0.344851
6 0.325114 -0.368508 1.013749 0.069613
7 2.055862 -1.085238 0.276277 -0.081811
8 -1.876217 -1.058380 -0.409820 -1.029904
9 0.386319 -1.906937 0.075222 0.120449
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.565032 -1.607176
1 bar one 1.308391 0.990335
2 foo two -1.252675 0.415938
3 bar three -1.685600 -1.520058
4 foo two 1.587265 -1.453618
5 bar two -1.505516 2.071624
6 foo one -0.258125 1.156111
7 foo three -0.572976 -0.295718
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.882725 1.541902
foo -1.061543 -1.784464
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 1.308391 0.990335
three -1.685600 -1.520058
two -1.505516 2.071624
foo one -0.823157 -0.451065
three -0.572976 -0.295718
two 0.334590 -1.037681
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 0x7fc331c70090>

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.446503 -1.246108 2.302081 0.185348
1 2000-01-02 -1.426874 -2.512547 3.064252 0.129371
2 2000-01-03 -0.899882 -2.238935 1.691353 0.952471
3 2000-01-04 0.296918 -2.522751 1.665118 1.918964
4 2000-01-05 0.748298 -2.625772 1.079004 0.972642
.. ... ... ... ... ...
995 2002-09-22 36.721154 15.031687 25.888191 4.402686
996 2002-09-23 35.773785 15.712163 26.392070 4.865123
997 2002-09-24 36.220666 15.497736 28.012235 6.078988
998 2002-09-25 35.427897 14.468245 27.108731 6.307152
999 2002-09-26 36.541143 13.555077 27.968725 5.945080
[1000 rows x 5 columns]