10 分钟入门 Mars DataFrame

本页面是一个对 Mars DataFrame 的简短介绍,内容修改自 10 分钟入门 pandas

如果没有说明,我们默认导入下面的包:

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 0x7fbadb5d8590>

创建对象

通过传入一个包含值的 list 来创建 Series 实例,并使用默认的整数索引:

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

通过一个 Mars Tensor 来创建 DataFrame 实例,并使用时间日期索引和列标签:

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.072369  0.135394  1.511647 -0.762108
2013-01-02 -1.855885  0.437674  0.184163 -0.212743
2013-01-03  0.976736  0.617389  0.033707  0.405372
2013-01-04 -0.049869 -1.117263  0.031380 -1.149751
2013-01-05 -1.347081  0.136575 -0.316038  0.153318
2013-01-06  0.833149 -0.106790  0.488973  0.009629

通过值可转换为序列的字典来创建 DataFrame 实例:

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

最终生成的 DataFrame 中,每列的类型均不相同。

In [13]: df2.dtypes
Out[13]: 
A           float64
B    datetime64[ns]
C           float32
D             int32
E            object
dtype: object

查看数据

下面是显示 DataFrame 中开头和结尾若干行的方法:

In [14]: df.head().execute()
Out[14]: 
                   A         B         C         D
2013-01-01  0.072369  0.135394  1.511647 -0.762108
2013-01-02 -1.855885  0.437674  0.184163 -0.212743
2013-01-03  0.976736  0.617389  0.033707  0.405372
2013-01-04 -0.049869 -1.117263  0.031380 -1.149751
2013-01-05 -1.347081  0.136575 -0.316038  0.153318

In [15]: df.tail(3).execute()
Out[15]: 
                   A         B         C         D
2013-01-04 -0.049869 -1.117263  0.031380 -1.149751
2013-01-05 -1.347081  0.136575 -0.316038  0.153318
2013-01-06  0.833149 -0.106790  0.488973  0.009629

显示索引和列:

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() 将 DataFrame 中的数据转换为 Mars Tensor 表示。注意当 DataFrame 中的列类型不同时,该操作可能代价很高。这也揭示了 DataFrame 和 Tensor 之间一项最基本的差异:在 Tensor 中,对于整个 Tensor 对象只有一个 dtype,但 DataFrame 对每列都有一个 dtype。当调用 DataFrame.to_tensor() 时,Mars DataFrame 将会找出一个可存储 DataFrame 中 所有 对象的 dtype,这可能是一个 object,并将导致 DataFrame 中的每个值都被转换为一个 Python 对象。

在上面的 df 对象中,DataFrame 实例中的值均为浮点数,因而 DataFrame.to_tensor() 执行速度会很快,且不需要数据复制。

In [18]: df.to_tensor().execute()
Out[18]: 
array([[ 0.07236881,  0.13539364,  1.51164732, -0.76210805],
       [-1.85588504,  0.43767361,  0.18416273, -0.21274268],
       [ 0.97673646,  0.61738877,  0.03370726,  0.40537162],
       [-0.04986856, -1.11726295,  0.03138035, -1.14975147],
       [-1.34708109,  0.13657522, -0.31603779,  0.15331799],
       [ 0.83314856, -0.10678966,  0.48897311,  0.00962943]])

而对于 df2 对象,DataFrame 实例中有不同的数据类型,因而 DataFrame.to_tensor() 执行代价就相对较高了。

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)

注解

DataFrame.to_tensor() 在输出结果中 不保留 索引或列标签。

describe() 将会为你的数据显示一份简单的统计摘要:

In [20]: df.describe().execute()
Out[20]: 
              A         B         C         D
count  6.000000  6.000000  6.000000  6.000000
mean  -0.228430  0.017163  0.322305 -0.259381
std    1.149063  0.611167  0.638248  0.588600
min   -1.855885 -1.117263 -0.316038 -1.149751
25%   -1.022778 -0.046244  0.031962 -0.624767
50%    0.011250  0.135984  0.108935 -0.101557
75%    0.642954  0.362399  0.412771  0.117396
max    0.976736  0.617389  1.511647  0.405372

按坐标排序:

In [21]: df.sort_index(axis=1, ascending=False).execute()
Out[21]: 
                   D         C         B         A
2013-01-01 -0.762108  1.511647  0.135394  0.072369
2013-01-02 -0.212743  0.184163  0.437674 -1.855885
2013-01-03  0.405372  0.033707  0.617389  0.976736
2013-01-04 -1.149751  0.031380 -1.117263 -0.049869
2013-01-05  0.153318 -0.316038  0.136575 -1.347081
2013-01-06  0.009629  0.488973 -0.106790  0.833149

按值排序:

In [22]: df.sort_values(by='B').execute()
Out[22]: 
                   A         B         C         D
2013-01-04 -0.049869 -1.117263  0.031380 -1.149751
2013-01-06  0.833149 -0.106790  0.488973  0.009629
2013-01-01  0.072369  0.135394  1.511647 -0.762108
2013-01-05 -1.347081  0.136575 -0.316038  0.153318
2013-01-02 -1.855885  0.437674  0.184163 -0.212743
2013-01-03  0.976736  0.617389  0.033707  0.405372

选择数据

注解

尽管在交互式分析场景下,使用标准的 Python / Numpy 表达式选择和设置 DataFrame 数据非常自然且便于使用,但对生产代码,我们推荐使用经过优化的数据访问方法,即 .at.iat.loc.iloc

获取数据

选择一列,将返回一个 Series 实例。这一操作等价于 df.A

In [23]: df['A'].execute()
Out[23]: 
2013-01-01    0.072369
2013-01-02   -1.855885
2013-01-03    0.976736
2013-01-04   -0.049869
2013-01-05   -1.347081
2013-01-06    0.833149
Freq: D, Name: A, dtype: float64

通过 [] 选择数据,将在行中选取。

In [24]: df[0:3].execute()
Out[24]: 
                   A         B         C         D
2013-01-01  0.072369  0.135394  1.511647 -0.762108
2013-01-02 -1.855885  0.437674  0.184163 -0.212743
2013-01-03  0.976736  0.617389  0.033707  0.405372

In [25]: df['20130102':'20130104'].execute()
Out[25]: 
                   A         B         C         D
2013-01-02 -1.855885  0.437674  0.184163 -0.212743
2013-01-03  0.976736  0.617389  0.033707  0.405372
2013-01-04 -0.049869 -1.117263  0.031380 -1.149751

按标签选择数据

通过行标签选择一行数据:

In [26]: df.loc['20130101'].execute()
Out[26]: 
A    0.072369
B    0.135394
C    1.511647
D   -0.762108
Name: 2013-01-01 00:00:00, dtype: float64

在特定坐标上指定标签:

In [27]: df.loc[:, ['A', 'B']].execute()
Out[27]: 
                   A         B
2013-01-01  0.072369  0.135394
2013-01-02 -1.855885  0.437674
2013-01-03  0.976736  0.617389
2013-01-04 -0.049869 -1.117263
2013-01-05 -1.347081  0.136575
2013-01-06  0.833149 -0.106790

在多个坐标上指定标签,带有这些标签的 所有数据 均会被选取:

In [28]: df.loc['20130102':'20130104', ['A', 'B']].execute()
Out[28]: 
                   A         B
2013-01-02 -1.855885  0.437674
2013-01-03  0.976736  0.617389
2013-01-04 -0.049869 -1.117263

在特定坐标上降低返回对象的维度:

In [29]: df.loc['20130102', ['A', 'B']].execute()
Out[29]: 
A   -1.855885
B    0.437674
Name: 2013-01-02 00:00:00, dtype: float64

获得一个常量:

In [30]: df.loc['20130101', 'A'].execute()
Out[30]: 0.07236880580862753

快速获取一个常数(和前述方法等价):

In [31]: df.at['20130101', 'A'].execute()
Out[31]: 0.07236880580862753

按位置选择

通过传入的整数选择相应位置的数据:

In [32]: df.iloc[3].execute()
Out[32]: 
A   -0.049869
B   -1.117263
C    0.031380
D   -1.149751
Name: 2013-01-04 00:00:00, dtype: float64

通过整数切片来选择数据,与 Numpy / Python 行为一致:

In [33]: df.iloc[3:5, 0:2].execute()
Out[33]: 
                   A         B
2013-01-04 -0.049869 -1.117263
2013-01-05 -1.347081  0.136575

通过整数列表选择相应位置的数据,与 Numpy / Python 行为一致:

In [34]: df.iloc[[1, 2, 4], [0, 2]].execute()
Out[34]: 
                   A         C
2013-01-02 -1.855885  0.184163
2013-01-03  0.976736  0.033707
2013-01-05 -1.347081 -0.316038

显示对行切片:

In [35]: df.iloc[1:3, :].execute()
Out[35]: 
                   A         B         C         D
2013-01-02 -1.855885  0.437674  0.184163 -0.212743
2013-01-03  0.976736  0.617389  0.033707  0.405372

显示对列切片:

In [36]: df.iloc[:, 1:3].execute()
Out[36]: 
                   B         C
2013-01-01  0.135394  1.511647
2013-01-02  0.437674  0.184163
2013-01-03  0.617389  0.033707
2013-01-04 -1.117263  0.031380
2013-01-05  0.136575 -0.316038
2013-01-06 -0.106790  0.488973

显示获取某个位置的常数:

In [37]: df.iloc[1, 1].execute()
Out[37]: 0.4376736100604306

快速获取一个常数(和前述方法等价):

In [38]: df.iat[1, 1].execute()
Out[38]: 0.4376736100604306

布尔索引

使用一行布尔值选择数据:

In [39]: df[df['A'] > 0].execute()
Out[39]: 
                   A         B         C         D
2013-01-01  0.072369  0.135394  1.511647 -0.762108
2013-01-03  0.976736  0.617389  0.033707  0.405372
2013-01-06  0.833149 -0.106790  0.488973  0.009629

从 DataFrame 选择满足某个布尔条件的值:

In [40]: df[df > 0].execute()
Out[40]: 
                   A         B         C         D
2013-01-01  0.072369  0.135394  1.511647       NaN
2013-01-02       NaN  0.437674  0.184163       NaN
2013-01-03  0.976736  0.617389  0.033707  0.405372
2013-01-04       NaN       NaN  0.031380       NaN
2013-01-05       NaN  0.136575       NaN  0.153318
2013-01-06  0.833149       NaN  0.488973  0.009629

数据操作

统计

除缺失值外的常见操作:

计算描述统计值:

In [41]: df.mean().execute()
Out[41]: 
A   -0.228430
B    0.017163
C    0.322305
D   -0.259381
dtype: float64

在另一条坐标轴上进行相同的操作:

In [42]: df.mean(1).execute()
Out[42]: 
2013-01-01    0.239325
2013-01-02   -0.361698
2013-01-03    0.508301
2013-01-04   -0.571376
2013-01-05   -0.343306
2013-01-06    0.306240
Freq: D, dtype: float64

在维度不同的对象上进行操作,这需要进行对齐。此外,Mars DataFrame 会自动在给定的坐标轴上对数据进行广播操作。

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.023264 -0.382611 -0.966293 -0.594628
2013-01-04 -3.049869 -4.117263 -2.968620 -4.149751
2013-01-05 -6.347081 -4.863425 -5.316038 -4.846682
2013-01-06       NaN       NaN       NaN       NaN

应用函数

在数据上应用函数:

In [46]: df.apply(lambda x: x.max() - x.min()).execute()
Out[46]: 
A    2.832622
B    1.734652
C    1.827685
D    1.555123
dtype: float64

字符串方法

如同下面的例子展示的那样,Series 对象通过 str 属性提供了一系列字符串操作方法以便于操作每一个元素。注意通过 str 进行的模式匹配通常会默认(在某些情形下会一直)用到 正则表达式 。更多的信息可在 向量化字符串方法 中查看。

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

数据合并

拼接

Mars DataFrame 提供一系列的方法方便地将 Series 和 DataFrame 对象连接到一起。这些方法基于一系列在索引上的集合逻辑以及关系代数上的功能来实现 Join / 合并这样的操作。

通过 concat(): 拼接 DataFrame 对象:

In [49]: df = md.DataFrame(mt.random.randn(10, 4))

In [50]: df.execute()
Out[50]: 
          0         1         2         3
0  0.864715 -0.205526  0.644030 -0.819021
1 -0.250032  0.959008  0.046298  1.544772
2 -0.650033 -0.145064  1.421081  0.267791
3  0.096983 -1.280004 -0.005014  1.513370
4  1.398290  1.206684 -0.868304 -0.006207
5  0.154180 -1.168906 -0.364102 -0.437500
6  0.216426 -1.127564 -0.049313  0.029825
7  1.519039 -0.158030 -0.321550  0.055976
8  0.384306  1.086999  0.538111  0.457117
9 -0.536919 -0.745852 -1.609891 -0.649652

# 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.864715 -0.205526  0.644030 -0.819021
1 -0.250032  0.959008  0.046298  1.544772
2 -0.650033 -0.145064  1.421081  0.267791
3  0.096983 -1.280004 -0.005014  1.513370
4  1.398290  1.206684 -0.868304 -0.006207
5  0.154180 -1.168906 -0.364102 -0.437500
6  0.216426 -1.127564 -0.049313  0.029825
7  1.519039 -0.158030 -0.321550  0.055976
8  0.384306  1.086999  0.538111  0.457117
9 -0.536919 -0.745852 -1.609891 -0.649652

注解

DataFrame 增加一列是相对较为高效的,但增加一行需要数据复制,因而可能会比较昂贵。我们建议向 DataFrame 的构造函数传入一系列预先填充的列表来构建 DataFrame 而不是向 DataFrame 迭代追加数据。

Join

SQL 样式的数据合并。参考 Database style joining 章节以获取更多信息。

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

另一个可供参考的例子如下:

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

分组

当提到“分组”时,我们指的是下面一个或多个步骤组成的过程:

  • 拆分 :根据某些条件将数据拆分成组

  • 应用函数 :对每一组数据分别应用某个函数

  • 合并 :将结果合并为一组数据

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.309425 -1.902364
1  bar    one  0.574578 -0.915844
2  foo    two  1.235790 -0.280777
3  bar  three -0.148293  0.780253
4  foo    two  1.700930 -0.339125
5  bar    two -0.492083  0.642134
6  foo    one -0.143564  0.343644
7  foo  three  1.265646  1.755934

分组,然后在结果上执行 sum() 函数。

In [65]: df.groupby('A').sum().execute()
Out[65]: 
            C         D
A                      
bar -0.065798  0.506544
foo  4.368227 -0.422688

我们也可以利用多列进行分组,这将形成一个多重索引。在此结果上,我们也可以执行 sum 函数。

In [66]: df.groupby(['A', 'B']).sum().execute()
Out[66]: 
                  C         D
A   B                        
bar one    0.574578 -0.915844
    three -0.148293  0.780253
    two   -0.492083  0.642134
foo one    0.165860 -1.558720
    three  1.265646  1.755934
    two    2.936721 -0.619902

绘图

我们使用标准的约定来引用 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:>
../../_images/series_plot_basic.png

在 DataFrame 中, plot() 方法可用于方便地绘制带有标签的行数据:

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 0x7fbaddda5c10>
../../_images/frame_plot_basic.png

读取和写入数据

CSV

In [77]: df.to_csv('foo.csv').execute()
Out[77]: 
Empty DataFrame
Columns: []
Index: []

从 CSV 文件读取数据

In [78]: md.read_csv('foo.csv').execute()
Out[78]: 
     Unnamed: 0          A          B         C          D
0    2000-01-01   0.620297  -1.205761 -0.772492   0.637089
1    2000-01-02   2.286827  -1.152575 -2.219168  -0.718913
2    2000-01-03   2.106041  -1.793255 -4.816947  -1.334365
3    2000-01-04   2.316656  -4.674498 -3.186240  -2.005781
4    2000-01-05   2.338883  -4.622292 -0.890634  -1.130675
..          ...        ...        ...       ...        ...
995  2002-09-22  58.225295  48.255798 -2.661115 -19.310245
996  2002-09-23  59.126044  46.625187 -4.306127 -20.342964
997  2002-09-24  60.344009  47.943595 -3.876789 -19.033403
998  2002-09-25  61.360336  48.130235 -3.910688 -19.264313
999  2002-09-26  62.136154  47.922637 -2.813047 -18.335893

[1000 rows x 5 columns]