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

创建对象

通过传入一个包含值的 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.995203  0.120425 -1.337194  0.968025
2013-01-02  0.229729  0.579713 -0.989094  1.667935
2013-01-03  1.849773  0.858858  1.430418  0.652273
2013-01-04 -0.937890 -0.388807  0.107982  1.470128
2013-01-05 -0.224552 -0.342468 -1.384782  1.678367
2013-01-06  0.465127  0.817153 -0.379626 -0.886900

通过值可转换为序列的字典来创建 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.995203  0.120425 -1.337194  0.968025
2013-01-02  0.229729  0.579713 -0.989094  1.667935
2013-01-03  1.849773  0.858858  1.430418  0.652273
2013-01-04 -0.937890 -0.388807  0.107982  1.470128
2013-01-05 -0.224552 -0.342468 -1.384782  1.678367

In [15]: df.tail(3).execute()
Out[15]: 
                   A         B         C         D
2013-01-04 -0.937890 -0.388807  0.107982  1.470128
2013-01-05 -0.224552 -0.342468 -1.384782  1.678367
2013-01-06  0.465127  0.817153 -0.379626 -0.886900

显示索引和列:

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.99520294,  0.12042502, -1.33719402,  0.96802529],
       [ 0.22972942,  0.57971268, -0.98909416,  1.66793454],
       [ 1.84977308,  0.85885815,  1.43041774,  0.65227295],
       [-0.9378896 , -0.38880654,  0.1079815 ,  1.47012764],
       [-0.22455201, -0.34246795, -1.38478168,  1.67836729],
       [ 0.46512714,  0.81715312, -0.37962575, -0.88689958]])

而对于 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.064498  0.274146 -0.425383  0.924971
std    1.057006  0.560975  1.077050  0.977332
min   -0.995203 -0.388807 -1.384782 -0.886900
25%   -0.759555 -0.226745 -1.250169  0.731211
50%    0.002589  0.350069 -0.684360  1.219076
75%    0.406278  0.757793 -0.013920  1.618483
max    1.849773  0.858858  1.430418  1.678367

按坐标排序:

In [21]: df.sort_index(axis=1, ascending=False).execute()
Out[21]: 
                   D         C         B         A
2013-01-01  0.968025 -1.337194  0.120425 -0.995203
2013-01-02  1.667935 -0.989094  0.579713  0.229729
2013-01-03  0.652273  1.430418  0.858858  1.849773
2013-01-04  1.470128  0.107982 -0.388807 -0.937890
2013-01-05  1.678367 -1.384782 -0.342468 -0.224552
2013-01-06 -0.886900 -0.379626  0.817153  0.465127

按值排序:

In [22]: df.sort_values(by='B').execute()
Out[22]: 
                   A         B         C         D
2013-01-04 -0.937890 -0.388807  0.107982  1.470128
2013-01-05 -0.224552 -0.342468 -1.384782  1.678367
2013-01-01 -0.995203  0.120425 -1.337194  0.968025
2013-01-02  0.229729  0.579713 -0.989094  1.667935
2013-01-06  0.465127  0.817153 -0.379626 -0.886900
2013-01-03  1.849773  0.858858  1.430418  0.652273

选择数据

注解

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

获取数据

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

In [23]: df['A'].execute()
Out[23]: 
2013-01-01   -0.995203
2013-01-02    0.229729
2013-01-03    1.849773
2013-01-04   -0.937890
2013-01-05   -0.224552
2013-01-06    0.465127
Freq: D, Name: A, dtype: float64

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

In [24]: df[0:3].execute()
Out[24]: 
                   A         B         C         D
2013-01-01 -0.995203  0.120425 -1.337194  0.968025
2013-01-02  0.229729  0.579713 -0.989094  1.667935
2013-01-03  1.849773  0.858858  1.430418  0.652273

In [25]: df['20130102':'20130104'].execute()
Out[25]: 
                   A         B         C         D
2013-01-02  0.229729  0.579713 -0.989094  1.667935
2013-01-03  1.849773  0.858858  1.430418  0.652273
2013-01-04 -0.937890 -0.388807  0.107982  1.470128

按标签选择数据

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

In [26]: df.loc['20130101'].execute()
Out[26]: 
A   -0.995203
B    0.120425
C   -1.337194
D    0.968025
Name: 2013-01-01 00:00:00, dtype: float64

在特定坐标上指定标签:

In [27]: df.loc[:, ['A', 'B']].execute()
Out[27]: 
                   A         B
2013-01-01 -0.995203  0.120425
2013-01-02  0.229729  0.579713
2013-01-03  1.849773  0.858858
2013-01-04 -0.937890 -0.388807
2013-01-05 -0.224552 -0.342468
2013-01-06  0.465127  0.817153

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

In [28]: df.loc['20130102':'20130104', ['A', 'B']].execute()
Out[28]: 
                   A         B
2013-01-02  0.229729  0.579713
2013-01-03  1.849773  0.858858
2013-01-04 -0.937890 -0.388807

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

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

获得一个常量:

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

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

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

按位置选择

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

In [32]: df.iloc[3].execute()
Out[32]: 
A   -0.937890
B   -0.388807
C    0.107982
D    1.470128
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.937890 -0.388807
2013-01-05 -0.224552 -0.342468

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

In [34]: df.iloc[[1, 2, 4], [0, 2]].execute()
Out[34]: 
                   A         C
2013-01-02  0.229729 -0.989094
2013-01-03  1.849773  1.430418
2013-01-05 -0.224552 -1.384782

显示对行切片:

In [35]: df.iloc[1:3, :].execute()
Out[35]: 
                   A         B         C         D
2013-01-02  0.229729  0.579713 -0.989094  1.667935
2013-01-03  1.849773  0.858858  1.430418  0.652273

显示对列切片:

In [36]: df.iloc[:, 1:3].execute()
Out[36]: 
                   B         C
2013-01-01  0.120425 -1.337194
2013-01-02  0.579713 -0.989094
2013-01-03  0.858858  1.430418
2013-01-04 -0.388807  0.107982
2013-01-05 -0.342468 -1.384782
2013-01-06  0.817153 -0.379626

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

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

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

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

布尔索引

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

In [39]: df[df['A'] > 0].execute()
Out[39]: 
                   A         B         C         D
2013-01-02  0.229729  0.579713 -0.989094  1.667935
2013-01-03  1.849773  0.858858  1.430418  0.652273
2013-01-06  0.465127  0.817153 -0.379626 -0.886900

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

In [40]: df[df > 0].execute()
Out[40]: 
                   A         B         C         D
2013-01-01       NaN  0.120425       NaN  0.968025
2013-01-02  0.229729  0.579713       NaN  1.667935
2013-01-03  1.849773  0.858858  1.430418  0.652273
2013-01-04       NaN       NaN  0.107982  1.470128
2013-01-05       NaN       NaN       NaN  1.678367
2013-01-06  0.465127  0.817153       NaN       NaN

数据操作

统计

除缺失值外的常见操作:

计算描述统计值:

In [41]: df.mean().execute()
Out[41]: 
A    0.064498
B    0.274146
C   -0.425383
D    0.924971
dtype: float64

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

In [42]: df.mean(1).execute()
Out[42]: 
2013-01-01   -0.310987
2013-01-02    0.372071
2013-01-03    1.197830
2013-01-04    0.062853
2013-01-05   -0.068359
2013-01-06    0.003939
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.849773 -0.141142  0.430418 -0.347727
2013-01-04 -3.937890 -3.388807 -2.892018 -1.529872
2013-01-05 -5.224552 -5.342468 -6.384782 -3.321633
2013-01-06       NaN       NaN       NaN       NaN

应用函数

在数据上应用函数:

In [46]: df.apply(lambda x: x.max() - x.min()).execute()
Out[46]: 
A    2.844976
B    1.247665
C    2.815199
D    2.565267
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.592253 -0.488671  1.298349 -0.754799
1  0.162921  0.729341  0.223247 -2.015034
2 -1.201571  0.979843  1.263713  1.477838
3 -0.286197  2.398072 -1.229230 -0.411331
4 -0.864936 -0.242507  0.775296  1.524644
5 -1.373199  0.589543 -0.366347 -0.962353
6 -1.030827 -0.026824  1.865253  0.216586
7  2.239148 -0.664769 -0.348151 -0.083107
8 -0.600186 -0.478322 -0.648520  0.453799
9 -0.651885 -0.246120 -0.534356  1.062471

# 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.592253 -0.488671  1.298349 -0.754799
1  0.162921  0.729341  0.223247 -2.015034
2 -1.201571  0.979843  1.263713  1.477838
3 -0.286197  2.398072 -1.229230 -0.411331
4 -0.864936 -0.242507  0.775296  1.524644
5 -1.373199  0.589543 -0.366347 -0.962353
6 -1.030827 -0.026824  1.865253  0.216586
7  2.239148 -0.664769 -0.348151 -0.083107
8 -0.600186 -0.478322 -0.648520  0.453799
9 -0.651885 -0.246120 -0.534356  1.062471

注解

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.663928 -0.279728
1  bar    one  0.198674  0.565689
2  foo    two -0.152476  0.708729
3  bar  three  0.792234  0.617776
4  foo    two -0.749429  0.213886
5  bar    two -0.105847  0.907304
6  foo    one -0.383825 -0.062569
7  foo  three -1.616166 -1.312149

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

In [65]: df.groupby('A').sum().execute()
Out[65]: 
            C        D
A                     
bar  0.885061  2.09077
foo -2.237968 -0.73183

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

In [66]: df.groupby(['A', 'B']).sum().execute()
Out[66]: 
                  C         D
A   B                        
bar one    0.198674  0.565689
    three  0.792234  0.617776
    two   -0.105847  0.907304
foo one    0.280103 -0.342297
    three -1.616166 -1.312149
    two   -0.901906  0.922616

绘图

我们使用标准的约定来引用 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 0x7fa09169ac90>
../../_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.176251  -0.612943 -1.285731  -2.519430
1    2000-01-02  -0.924568  -0.093349 -2.082806  -2.444421
2    2000-01-03   0.052093   0.049649 -0.895402  -3.250718
3    2000-01-04  -0.963021   0.276143 -1.833775  -1.617076
4    2000-01-05  -2.286037  -0.447774 -1.735580  -1.773235
..          ...        ...        ...       ...        ...
995  2002-09-22 -33.473782 -26.941157 -0.778590  27.374324
996  2002-09-23 -33.316099 -27.703960  0.070036  25.815902
997  2002-09-24 -34.396609 -27.615110  0.174335  25.807905
998  2002-09-25 -33.898357 -28.073798 -0.114224  25.465008
999  2002-09-26 -34.667253 -28.835121  1.096754  26.016300

[1000 rows x 5 columns]