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 0x7f27fed05710>
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.031858 -1.288816 0.854701 -1.335960
2013-01-02 -0.401715 -0.615244 0.552401 -0.430028
2013-01-03 -0.870396 1.550893 -2.725728 0.959227
2013-01-04 1.028434 0.339197 0.380672 0.636182
2013-01-05 1.158726 -1.267667 -2.122808 0.455100
2013-01-06 -0.407456 1.736010 0.180603 0.781140
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.031858 -1.288816 0.854701 -1.335960
2013-01-02 -0.401715 -0.615244 0.552401 -0.430028
2013-01-03 -0.870396 1.550893 -2.725728 0.959227
2013-01-04 1.028434 0.339197 0.380672 0.636182
2013-01-05 1.158726 -1.267667 -2.122808 0.455100
In [15]: df.tail(3).execute()
Out[15]:
A B C D
2013-01-04 1.028434 0.339197 0.380672 0.636182
2013-01-05 1.158726 -1.267667 -2.122808 0.455100
2013-01-06 -0.407456 1.736010 0.180603 0.781140
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.03185849, -1.28881595, 0.8547013 , -1.33596011],
[-0.40171494, -0.61524382, 0.55240138, -0.43002834],
[-0.87039601, 1.55089252, -2.72572773, 0.95922729],
[ 1.02843429, 0.33919688, 0.3806717 , 0.63618186],
[ 1.15872567, -1.26766728, -2.12280763, 0.45509978],
[-0.40745647, 1.73601006, 0.18060267, 0.78113959]])
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.089909 0.075729 -0.480026 0.177610
std 0.829195 1.352494 1.534050 0.885729
min -0.870396 -1.288816 -2.725728 -1.335960
25% -0.406021 -1.104561 -1.546955 -0.208746
50% -0.184928 -0.138023 0.280637 0.545641
75% 0.779290 1.247969 0.509469 0.744900
max 1.158726 1.736010 0.854701 0.959227
Sorting by an axis:
In [21]: df.sort_index(axis=1, ascending=False).execute()
Out[21]:
D C B A
2013-01-01 -1.335960 0.854701 -1.288816 0.031858
2013-01-02 -0.430028 0.552401 -0.615244 -0.401715
2013-01-03 0.959227 -2.725728 1.550893 -0.870396
2013-01-04 0.636182 0.380672 0.339197 1.028434
2013-01-05 0.455100 -2.122808 -1.267667 1.158726
2013-01-06 0.781140 0.180603 1.736010 -0.407456
Sorting by values:
In [22]: df.sort_values(by='B').execute()
Out[22]:
A B C D
2013-01-01 0.031858 -1.288816 0.854701 -1.335960
2013-01-05 1.158726 -1.267667 -2.122808 0.455100
2013-01-02 -0.401715 -0.615244 0.552401 -0.430028
2013-01-04 1.028434 0.339197 0.380672 0.636182
2013-01-03 -0.870396 1.550893 -2.725728 0.959227
2013-01-06 -0.407456 1.736010 0.180603 0.781140
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.031858
2013-01-02 -0.401715
2013-01-03 -0.870396
2013-01-04 1.028434
2013-01-05 1.158726
2013-01-06 -0.407456
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.031858 -1.288816 0.854701 -1.335960
2013-01-02 -0.401715 -0.615244 0.552401 -0.430028
2013-01-03 -0.870396 1.550893 -2.725728 0.959227
In [25]: df['20130102':'20130104'].execute()
Out[25]:
A B C D
2013-01-02 -0.401715 -0.615244 0.552401 -0.430028
2013-01-03 -0.870396 1.550893 -2.725728 0.959227
2013-01-04 1.028434 0.339197 0.380672 0.636182
Selection by label¶
For getting a cross section using a label:
In [26]: df.loc['20130101'].execute()
Out[26]:
A 0.031858
B -1.288816
C 0.854701
D -1.335960
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.031858 -1.288816
2013-01-02 -0.401715 -0.615244
2013-01-03 -0.870396 1.550893
2013-01-04 1.028434 0.339197
2013-01-05 1.158726 -1.267667
2013-01-06 -0.407456 1.736010
Showing label slicing, both endpoints are included:
In [28]: df.loc['20130102':'20130104', ['A', 'B']].execute()
Out[28]:
A B
2013-01-02 -0.401715 -0.615244
2013-01-03 -0.870396 1.550893
2013-01-04 1.028434 0.339197
Reduction in the dimensions of the returned object:
In [29]: df.loc['20130102', ['A', 'B']].execute()
Out[29]:
A -0.401715
B -0.615244
Name: 2013-01-02 00:00:00, dtype: float64
For getting a scalar value:
In [30]: df.loc['20130101', 'A'].execute()
Out[30]: 0.03185848999371285
For getting fast access to a scalar (equivalent to the prior method):
In [31]: df.at['20130101', 'A'].execute()
Out[31]: 0.03185848999371285
Selection by position¶
Select via the position of the passed integers:
In [32]: df.iloc[3].execute()
Out[32]:
A 1.028434
B 0.339197
C 0.380672
D 0.636182
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.028434 0.339197
2013-01-05 1.158726 -1.267667
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.401715 0.552401
2013-01-03 -0.870396 -2.725728
2013-01-05 1.158726 -2.122808
For slicing rows explicitly:
In [35]: df.iloc[1:3, :].execute()
Out[35]:
A B C D
2013-01-02 -0.401715 -0.615244 0.552401 -0.430028
2013-01-03 -0.870396 1.550893 -2.725728 0.959227
For slicing columns explicitly:
In [36]: df.iloc[:, 1:3].execute()
Out[36]:
B C
2013-01-01 -1.288816 0.854701
2013-01-02 -0.615244 0.552401
2013-01-03 1.550893 -2.725728
2013-01-04 0.339197 0.380672
2013-01-05 -1.267667 -2.122808
2013-01-06 1.736010 0.180603
For getting a value explicitly:
In [37]: df.iloc[1, 1].execute()
Out[37]: -0.6152438221607031
For getting fast access to a scalar (equivalent to the prior method):
In [38]: df.iat[1, 1].execute()
Out[38]: -0.6152438221607031
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.031858 -1.288816 0.854701 -1.335960
2013-01-04 1.028434 0.339197 0.380672 0.636182
2013-01-05 1.158726 -1.267667 -2.122808 0.455100
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.031858 NaN 0.854701 NaN
2013-01-02 NaN NaN 0.552401 NaN
2013-01-03 NaN 1.550893 NaN 0.959227
2013-01-04 1.028434 0.339197 0.380672 0.636182
2013-01-05 1.158726 NaN NaN 0.455100
2013-01-06 NaN 1.736010 0.180603 0.781140
Operations¶
Stats¶
Operations in general exclude missing data.
Performing a descriptive statistic:
In [41]: df.mean().execute()
Out[41]:
A 0.089909
B 0.075729
C -0.480026
D 0.177610
dtype: float64
Same operation on the other axis:
In [42]: df.mean(1).execute()
Out[42]:
2013-01-01 -0.434554
2013-01-02 -0.223646
2013-01-03 -0.271501
2013-01-04 0.596121
2013-01-05 -0.444162
2013-01-06 0.572574
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.870396 0.550893 -3.725728 -0.040773
2013-01-04 -1.971566 -2.660803 -2.619328 -2.363818
2013-01-05 -3.841274 -6.267667 -7.122808 -4.544900
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.029122
B 3.024826
C 3.580429
D 2.295187
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 1.120997 -0.118479 -2.355211 1.193455
1 1.075513 -1.389744 0.807168 0.309333
2 -0.069988 -0.064682 -2.005724 -1.207657
3 0.176942 -0.342839 -1.646610 -1.955171
4 -0.399223 -0.768995 -1.685051 1.133064
5 0.214478 0.695396 0.475005 0.825655
6 0.099625 1.812049 0.227001 -0.648604
7 0.846410 -0.466933 2.242083 -0.505739
8 -0.768976 -0.376062 -0.525003 -0.954622
9 -1.185568 0.773119 -0.671390 1.293160
# 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 1.120997 -0.118479 -2.355211 1.193455
1 1.075513 -1.389744 0.807168 0.309333
2 -0.069988 -0.064682 -2.005724 -1.207657
3 0.176942 -0.342839 -1.646610 -1.955171
4 -0.399223 -0.768995 -1.685051 1.133064
5 0.214478 0.695396 0.475005 0.825655
6 0.099625 1.812049 0.227001 -0.648604
7 0.846410 -0.466933 2.242083 -0.505739
8 -0.768976 -0.376062 -0.525003 -0.954622
9 -1.185568 0.773119 -0.671390 1.293160
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 1.066889 -0.099254
1 bar one 0.184610 -0.078819
2 foo two 0.451670 -0.018452
3 bar three -0.040137 -2.248390
4 foo two -0.487763 0.106860
5 bar two 0.246008 0.232604
6 foo one 0.145694 0.832487
7 foo three -0.121356 0.347842
Grouping and then applying the sum()
function to the resulting
groups.
In [65]: df.groupby('A').sum().execute()
Out[65]:
C D
A
bar 0.390481 -2.094605
foo 1.055134 1.169484
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.184610 -0.078819
three -0.040137 -2.248390
two 0.246008 0.232604
foo one 1.212583 0.733233
three -0.121356 0.347842
two -0.036093 0.088409
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 0x7f27fcf89e50>
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.178932 -0.387909 0.459451 -1.251097
1 2000-01-02 -1.861876 -0.713948 0.250925 -1.827832
2 2000-01-03 -2.778307 1.833456 1.612688 -0.942235
3 2000-01-04 -2.793780 1.291922 2.792795 -0.529351
4 2000-01-05 -2.481649 1.035656 2.795307 -0.520718
.. ... ... ... ... ...
995 2002-09-22 65.407966 -24.970449 13.954419 9.800957
996 2002-09-23 66.440976 -25.887778 15.257127 9.720813
997 2002-09-24 66.540299 -26.187824 14.320245 10.335813
998 2002-09-25 66.990436 -25.371995 14.733360 10.660733
999 2002-09-26 67.748928 -23.776976 14.499819 11.212591
[1000 rows x 5 columns]