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.tensor as mt In [2]: import mars.dataframe as md
Creating a Series by passing a list of values, letting it create a default integer index:
Series
In [3]: s = md.Series([1, 3, 5, mt.nan, 6, 8]) In [4]: s.execute() Out[4]: 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:
DataFrame
In [5]: dates = md.date_range('20130101', periods=6) In [6]: dates.execute() Out[6]: 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 [7]: df = md.DataFrame(mt.random.randn(6, 4), index=dates, columns=list('ABCD')) In [8]: df.execute() Out[8]: A B C D 2013-01-01 -0.102617 0.281239 0.765845 -1.721473 2013-01-02 1.286225 -1.990426 -0.470803 -1.370609 2013-01-03 -1.291403 -0.115962 -0.897020 -1.676863 2013-01-04 -0.681588 0.945126 0.070495 -0.584050 2013-01-05 -2.483265 0.080008 1.008448 -0.064077 2013-01-06 1.442641 0.292922 1.195201 2.459135
Creating a DataFrame by passing a dict of objects that can be converted to series-like.
In [9]: 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 [10]: df2.execute() Out[10]: 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 [11]: df2.dtypes Out[11]: A float64 B datetime64[ns] C float32 D int32 E object dtype: object
Here is how to view the top and bottom rows of the frame:
In [12]: df.head().execute() Out[12]: A B C D 2013-01-01 -0.102617 0.281239 0.765845 -1.721473 2013-01-02 1.286225 -1.990426 -0.470803 -1.370609 2013-01-03 -1.291403 -0.115962 -0.897020 -1.676863 2013-01-04 -0.681588 0.945126 0.070495 -0.584050 2013-01-05 -2.483265 0.080008 1.008448 -0.064077 In [13]: df.tail(3).execute() Out[13]: A B C D 2013-01-04 -0.681588 0.945126 0.070495 -0.584050 2013-01-05 -2.483265 0.080008 1.008448 -0.064077 2013-01-06 1.442641 0.292922 1.195201 2.459135
Display the index, columns:
In [14]: df.index.execute() Out[14]: 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 [15]: df.columns.execute() Out[15]: 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.
DataFrame.to_tensor()
object
For df, our DataFrame of all floating-point values, DataFrame.to_tensor() is fast and doesn’t require copying data.
df
In [16]: df.to_tensor().execute() Out[16]: array([[-0.10261746, 0.28123899, 0.76584499, -1.72147292], [ 1.28622519, -1.99042578, -0.47080276, -1.37060858], [-1.2914031 , -0.11596179, -0.89701989, -1.67686266], [-0.6815878 , 0.94512634, 0.07049495, -0.58404984], [-2.48326497, 0.08000753, 1.00844776, -0.06407699], [ 1.44264056, 0.29292199, 1.1952013 , 2.4591348 ]])
For df2, the DataFrame with multiple dtypes, DataFrame.to_tensor() is relatively expensive.
df2
In [17]: df2.to_tensor().execute() Out[17]: 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:
describe()
In [18]: df.describe().execute() Out[18]: A B C D count 6.000000 6.000000 6.000000 6.000000 mean -0.305001 -0.084515 0.278694 -0.492989 std 1.515708 0.999695 0.848203 1.586710 min -2.483265 -1.990426 -0.897020 -1.721473 25% -1.138949 -0.066969 -0.335478 -1.600299 50% -0.392103 0.180623 0.418170 -0.977329 75% 0.939015 0.290001 0.947797 -0.194070 max 1.442641 0.945126 1.195201 2.459135
Sorting by an axis:
In [19]: df.sort_index(axis=1, ascending=False).execute() Out[19]: D C B A 2013-01-01 -1.721473 0.765845 0.281239 -0.102617 2013-01-02 -1.370609 -0.470803 -1.990426 1.286225 2013-01-03 -1.676863 -0.897020 -0.115962 -1.291403 2013-01-04 -0.584050 0.070495 0.945126 -0.681588 2013-01-05 -0.064077 1.008448 0.080008 -2.483265 2013-01-06 2.459135 1.195201 0.292922 1.442641
Sorting by values:
In [20]: df.sort_values(by='B').execute() Out[20]: A B C D 2013-01-02 1.286225 -1.990426 -0.470803 -1.370609 2013-01-03 -1.291403 -0.115962 -0.897020 -1.676863 2013-01-05 -2.483265 0.080008 1.008448 -0.064077 2013-01-01 -0.102617 0.281239 0.765845 -1.721473 2013-01-06 1.442641 0.292922 1.195201 2.459135 2013-01-04 -0.681588 0.945126 0.070495 -0.584050
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.
.at
.iat
.loc
.iloc
Selecting a single column, which yields a Series, equivalent to df.A:
df.A
In [21]: df['A'].execute() Out[21]: 2013-01-01 -0.102617 2013-01-02 1.286225 2013-01-03 -1.291403 2013-01-04 -0.681588 2013-01-05 -2.483265 2013-01-06 1.442641 Freq: D, Name: A, dtype: float64
Selecting via [], which slices the rows.
[]
In [22]: df[0:3].execute() Out[22]: A B C D 2013-01-01 -0.102617 0.281239 0.765845 -1.721473 2013-01-02 1.286225 -1.990426 -0.470803 -1.370609 2013-01-03 -1.291403 -0.115962 -0.897020 -1.676863 In [23]: df['20130102':'20130104'].execute() Out[23]: A B C D 2013-01-02 1.286225 -1.990426 -0.470803 -1.370609 2013-01-03 -1.291403 -0.115962 -0.897020 -1.676863 2013-01-04 -0.681588 0.945126 0.070495 -0.584050
For getting a cross section using a label:
In [24]: df.loc['20130101'].execute() Out[24]: A -0.102617 B 0.281239 C 0.765845 D -1.721473 Name: 2013-01-01 00:00:00, dtype: float64
Selecting on a multi-axis by label:
In [25]: df.loc[:, ['A', 'B']].execute() Out[25]: A B 2013-01-01 -0.102617 0.281239 2013-01-02 1.286225 -1.990426 2013-01-03 -1.291403 -0.115962 2013-01-04 -0.681588 0.945126 2013-01-05 -2.483265 0.080008 2013-01-06 1.442641 0.292922
Showing label slicing, both endpoints are included:
In [26]: df.loc['20130102':'20130104', ['A', 'B']].execute() Out[26]: A B 2013-01-02 1.286225 -1.990426 2013-01-03 -1.291403 -0.115962 2013-01-04 -0.681588 0.945126
Reduction in the dimensions of the returned object:
In [27]: df.loc['20130102', ['A', 'B']].execute() Out[27]: A 1.286225 B -1.990426 Name: 2013-01-02 00:00:00, dtype: float64
For getting a scalar value:
In [28]: df.loc['20130101', 'A'].execute() Out[28]: -0.10261745872880973
For getting fast access to a scalar (equivalent to the prior method):
In [29]: df.at['20130101', 'A'].execute() Out[29]: -0.10261745872880973
Select via the position of the passed integers:
In [30]: df.iloc[3].execute() Out[30]: A -0.681588 B 0.945126 C 0.070495 D -0.584050 Name: 2013-01-04 00:00:00, dtype: float64
By integer slices, acting similar to numpy/python:
In [31]: df.iloc[3:5, 0:2].execute() Out[31]: A B 2013-01-04 -0.681588 0.945126 2013-01-05 -2.483265 0.080008
By lists of integer position locations, similar to the numpy/python style:
In [32]: df.iloc[[1, 2, 4], [0, 2]].execute() Out[32]: A C 2013-01-02 1.286225 -0.470803 2013-01-03 -1.291403 -0.897020 2013-01-05 -2.483265 1.008448
For slicing rows explicitly:
In [33]: df.iloc[1:3, :].execute() Out[33]: A B C D 2013-01-02 1.286225 -1.990426 -0.470803 -1.370609 2013-01-03 -1.291403 -0.115962 -0.897020 -1.676863
For slicing columns explicitly:
In [34]: df.iloc[:, 1:3].execute() Out[34]: B C 2013-01-01 0.281239 0.765845 2013-01-02 -1.990426 -0.470803 2013-01-03 -0.115962 -0.897020 2013-01-04 0.945126 0.070495 2013-01-05 0.080008 1.008448 2013-01-06 0.292922 1.195201
For getting a value explicitly:
In [35]: df.iloc[1, 1].execute() Out[35]: -1.99042577688373
In [36]: df.iat[1, 1].execute() Out[36]: -1.99042577688373
Using a single column’s values to select data.
In [37]: df[df['A'] > 0].execute() Out[37]: A B C D 2013-01-02 1.286225 -1.990426 -0.470803 -1.370609 2013-01-06 1.442641 0.292922 1.195201 2.459135
Selecting values from a DataFrame where a boolean condition is met.
In [38]: df[df > 0].execute() Out[38]: A B C D 2013-01-01 NaN 0.281239 0.765845 NaN 2013-01-02 1.286225 NaN NaN NaN 2013-01-03 NaN NaN NaN NaN 2013-01-04 NaN 0.945126 0.070495 NaN 2013-01-05 NaN 0.080008 1.008448 NaN 2013-01-06 1.442641 0.292922 1.195201 2.459135
Operations in general exclude missing data.
Performing a descriptive statistic:
In [39]: df.mean().execute() Out[39]: A -0.305001 B -0.084515 C 0.278694 D -0.492989 dtype: float64
Same operation on the other axis:
In [40]: df.mean(1).execute() Out[40]: 2013-01-01 -0.194252 2013-01-02 -0.636403 2013-01-03 -0.995312 2013-01-04 -0.062504 2013-01-05 -0.364722 2013-01-06 1.347475 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 [41]: s = md.Series([1, 3, 5, mt.nan, 6, 8], index=dates).shift(2) In [42]: s.execute() Out[42]: 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 [43]: df.sub(s, axis='index').execute() Out[43]: A B C D 2013-01-01 NaN NaN NaN NaN 2013-01-02 NaN NaN NaN NaN 2013-01-03 -2.291403 -1.115962 -1.897020 -2.676863 2013-01-04 -3.681588 -2.054874 -2.929505 -3.584050 2013-01-05 -7.483265 -4.919992 -3.991552 -5.064077 2013-01-06 NaN NaN NaN NaN
Applying functions to the data:
In [44]: df.apply(lambda x: x.max() - x.min()).execute() Out[44]: A 3.925906 B 2.935552 C 2.092221 D 4.180608 dtype: float64
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 [45]: s = md.Series(['A', 'B', 'C', 'Aaba', 'Baca', mt.nan, 'CABA', 'dog', 'cat']) In [46]: s.str.lower().execute() Out[46]: 0 a 1 b 2 c 3 aaba 4 baca 5 NaN 6 caba 7 dog 8 cat dtype: object
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():
concat()
In [47]: df = md.DataFrame(mt.random.randn(10, 4)) In [48]: df.execute() Out[48]: 0 1 2 3 0 -0.958207 -0.944926 0.898935 -0.070548 1 -0.218734 0.395159 1.184165 -0.381167 2 0.417184 -0.685930 0.959486 -0.565428 3 0.322161 -0.391164 -2.023050 -0.478529 4 0.342213 1.477304 1.155072 1.018949 5 0.923782 1.829053 -0.682229 -0.862974 6 -0.838076 -0.516523 1.094508 0.106442 7 0.399551 0.722962 1.054487 -0.220905 8 -0.463069 0.227922 -0.001813 1.743965 9 0.997896 -1.212283 1.831018 -0.211352 # break it into pieces In [49]: pieces = [df[:3], df[3:7], df[7:]] In [50]: md.concat(pieces).execute() Out[50]: 0 1 2 3 0 -0.958207 -0.944926 0.898935 -0.070548 1 -0.218734 0.395159 1.184165 -0.381167 2 0.417184 -0.685930 0.959486 -0.565428 3 0.322161 -0.391164 -2.023050 -0.478529 4 0.342213 1.477304 1.155072 1.018949 5 0.923782 1.829053 -0.682229 -0.862974 6 -0.838076 -0.516523 1.094508 0.106442 7 0.399551 0.722962 1.054487 -0.220905 8 -0.463069 0.227922 -0.001813 1.743965 9 0.997896 -1.212283 1.831018 -0.211352
Adding a column to a DataFrame is relatively fast. However, adding a row requires a copy, and may be expensive. We recommend passing a pre-built list of records to the DataFrame constructor instead of building a DataFrame by iteratively appending records to it.
SQL style merges. See the Database style joining section.
In [51]: left = md.DataFrame({'key': ['foo', 'foo'], 'lval': [1, 2]}) In [52]: right = md.DataFrame({'key': ['foo', 'foo'], 'rval': [4, 5]}) In [53]: left.execute() Out[53]: key lval 0 foo 1 1 foo 2 In [54]: right.execute() Out[54]: key rval 0 foo 4 1 foo 5 In [55]: md.merge(left, right, on='key').execute() Out[55]: 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 [56]: left = md.DataFrame({'key': ['foo', 'bar'], 'lval': [1, 2]}) In [57]: right = md.DataFrame({'key': ['foo', 'bar'], 'rval': [4, 5]}) In [58]: left.execute() Out[58]: key lval 0 foo 1 1 bar 2 In [59]: right.execute() Out[59]: key rval 0 foo 4 1 bar 5 In [60]: md.merge(left, right, on='key').execute() Out[60]: key lval rval 0 foo 1 4 1 bar 2 5
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
Splitting the data into groups based on some criteria
Applying a function to each group independently
Combining the results into a data structure
In [61]: 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 [62]: df.execute() Out[62]: A B C D 0 foo one 0.144543 0.326850 1 bar one -0.182791 0.034401 2 foo two -1.492649 0.303493 3 bar three -0.215409 1.034241 4 foo two 0.491883 1.063304 5 bar two 0.618155 1.569673 6 foo one -1.562122 0.432408 7 foo three -0.690482 0.207695
Grouping and then applying the sum() function to the resulting groups.
sum()
In [63]: df.groupby('A').sum().execute() Out[63]: C D A bar 0.219955 2.638315 foo -3.108828 2.333749
Grouping by multiple columns forms a hierarchical index, and again we can apply the sum function.
In [64]: df.groupby(['A', 'B']).sum().execute() Out[64]: C D A B foo one -1.417579 0.759258 two -1.000767 1.366796 three -0.690482 0.207695 bar one -0.182791 0.034401 two 0.618155 1.569673 three -0.215409 1.034241
We use the standard convention for referencing the matplotlib API:
In [65]: import matplotlib.pyplot as plt In [66]: plt.close('all')
In [67]: ts = md.Series(mt.random.randn(1000), ....: index=md.date_range('1/1/2000', periods=1000)) ....: In [68]: ts = ts.cumsum() In [69]: ts.plot() Out[69]: <AxesSubplot:>
On a DataFrame, the plot() method is a convenience to plot all of the columns with labels:
plot()
In [70]: df = md.DataFrame(mt.random.randn(1000, 4), index=ts.index, ....: columns=['A', 'B', 'C', 'D']) ....: In [71]: df = df.cumsum() In [72]: plt.figure() Out[72]: <Figure size 640x480 with 0 Axes> In [73]: df.plot() Out[73]: <AxesSubplot:> In [74]: plt.legend(loc='best') Out[74]: <matplotlib.legend.Legend at 0x7ff8ae815e90>
In [75]: df.to_csv('foo.csv').execute() Out[75]: Empty DataFrame Columns: [] Index: []
Reading from a csv file.
In [76]: md.read_csv('foo.csv').execute() Out[76]: Unnamed: 0 A B C D 0 2000-01-01 -0.135754 -1.479990 -0.750506 1.332619 1 2000-01-02 0.950278 -1.360197 -0.502147 1.744138 2 2000-01-03 0.713959 -2.006620 -0.653554 3.877728 3 2000-01-04 1.213436 -0.057034 0.224899 3.707546 4 2000-01-05 0.672141 0.695177 0.611897 3.409125 .. ... ... ... ... ... 995 2002-09-22 -26.686348 52.440448 -26.252941 2.677829 996 2002-09-23 -26.763264 53.322395 -26.425633 2.582568 997 2002-09-24 -26.147643 53.618595 -29.084498 2.919243 998 2002-09-25 -26.120828 53.276693 -29.080375 3.320198 999 2002-09-26 -27.257435 52.324406 -29.365879 3.118605 [1000 rows x 5 columns]