本文是对pandas 官方网站上《10 Minutes to pandas》的一个简单的翻译,原文在 这里 。这篇文章是对pandas的一个简单的介绍,详细的介绍请参考: Cookbook 。习惯上,我们会按下面格式引入所需要的包:
一、创建对象
可以通过 Data Structure Intro Setion 来查看有关该节内容的详细信息。
1、可以通过传递一个list对象来创建一个Series,pandas会默认创建整型索引:
2、通过传递一个numpy array,时间索引以及列标签来创建一个DataFrame:
In [6]: dates = pd.date_range('20130101', periods=6) In [7]: dates Out[7]: 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 [8]: df = pd.DataFrame(np.random.randn(6,4), index=dates, columns=list('ABCD')) In [9]: df Out[9]: A B C D 2013-01-01 0.469112 -0.282863 -1.509059 -1.135632 2013-01-02 1.212112 -0.173215 0.119209 -1.044236 2013-01-03 -0.861849 -2.104569 -0.494929 1.071804 2013-01-04 0.721555 -0.706771 -1.039575 0.271860 2013-01-05 -0.424972 0.567020 0.276232 -1.087401 2013-01-06 -0.673690 0.113648 -1.478427 0.524988
3、通过传递一个能够被转换成类似序列结构的字典对象来创建一个DataFrame:
In [10]: df2 = pd.DataFrame({ 'A' : 1., ....: 'B' : pd.Timestamp('20130102'), ....: 'C' : pd.Series(1,index=list(range(4)),dtype='float32'), ....: 'D' : np.array([3] * 4,dtype='int32'), ....: 'E' : pd.Categorical(["test","train","test","train"]), ....: 'F' : 'foo' }) ....: In [11]: df2 Out[11]: A B C D E F 0 1.0 2013-01-02 1.0 3 test foo 1 1.0 2013-01-02 1.0 3 train foo 2 1.0 2013-01-02 1.0 3 test foo 3 1.0 2013-01-02 1.0 3 train foo
4、查看不同列的数据类型:
5、如果你使用的是IPython,使用Tab自动补全功能会自动识别所有的属性以及自定义的列,下图中是所有能够被自动识别的属性的一个子集:
二、查看数据
详情请参阅: Basics Section
1、 查看frame中头部和尾部的行:
2、 显示索引、列和底层的numpy数据:
3、 describe()函数对于数据的快速统计汇总:
4、 对数据的转置:
5、 按轴进行排序
6、 按值进行排序
三、选择
虽然标准的Python/Numpy的选择和设置表达式都能够直接派上用场,但是作为工程使用的代码,我们推荐使用经过优化的pandas数据访问方式: .at , .iat , .loc , .iloc 和 .ix 详情请参阅 Indexing and Selecing Data 和 MultiIndex / Advanced Indexing 。
l 获取
1、 选择一个单独的列,这将会返回一个 Series ,等同于 df.A :
2、 通过 [] 进行选择,这将会对行进行切片
l 通过标签选择
1、 使用标签来获取一个交叉的区域
2、 通过标签来在多个轴上进行选择
3、 标签切片
4、 对于返回的对象进行维度缩减
5、 获取一个标量
6、 快速访问一个标量(与上一个方法等价)
l 通过位置选择
1、 通过传递数值进行位置选择(选择的是行)
2、 通过数值进行切片,与 numpy/python 中的情况类似
3、 通过指定一个位置的列表,与 numpy/python 中的情况类似
4、 对行进行切片
5、 对列进行切片
6、 获取特定的值
7、获得快速访问一个标量(相当于现有的方法)
l 布尔索引
1、 使用一个单独列的值来选择数据:
2、 使用 where 操作来选择数据:
3、 使用 isin() 方法来过滤:
l 设置
1、 设置一个新的列:
In [45]: s1 = pd.Series([1,2,3,4,5,6], index=pd.date_range('20130102', periods=6)) In [46]: s1 Out[46]: 2013-01-02 1 2013-01-03 2 2013-01-04 3 2013-01-05 4 2013-01-06 5 2013-01-07 6 Freq: D, dtype: int64 In [47]: df['F'] = s1
2、 通过标签设置新的值:
3、 通过位置设置新的值:
4、 通过一个 numpy 数组设置一组新值:
上述操作结果如下:
5、 通过 where 操作来设置新的值:
四、缺失值处理
在pandas中,使用np.nan来代替缺失值,这些值将默认不会包含在计算中,详情请参阅: Missing Data Section 。
1、 reindex()方法可以对指定轴上的索引进行改变/增加/删除操作,这将返回原始数据的一个拷贝:、
In [55]: df1 = df.reindex(index=dates[0:4], columns=list(df.columns) + ['E']) In [56]: df1.loc[dates[0]:dates[1],'E'] = 1 In [57]: df1 Out[57]: A B C D F E 2013-01-01 0.000000 0.000000 -1.509059 5 NaN 1.0 2013-01-02 1.212112 -0.173215 0.119209 5 1.0 1.0 2013-01-03 -0.861849 -2.104569 -0.494929 5 2.0 NaN 2013-01-04 0.721555 -0.706771 -1.039575 5 3.0 NaN
2、 去掉包含缺失值的行:
3、 对缺失值进行填充:
4、 对数据进行布尔填充:
五、相关操作
详情请参与 Basic Section On Binary Ops
l 统计(相关操作通常情况下不包括缺失值)
1、 执行描述性统计:
2、 在其他轴上进行相同的操作:
3、 对于拥有不同维度,需要对齐的对象进行操作。Pandas会自动的沿着指定的维度进行广播:
l Apply
1、 对数据应用函数:
l 直方图
具体请参照: Histogramming and Discretization
l 字符串方法
Series对象在其str属性中配备了一组字符串处理方法,可以很容易的应用到数组中的每个元素,如下段代码所示。更多详情请参考: Vectorized String Methods .
In [71]: s = pd.Series(['A', 'B', 'C', 'Aaba', 'Baca', np.nan, 'CABA', 'dog', 'cat']) In [72]: s.str.lower() Out[72]: 0 a 1 b 2 c 3 aaba 4 baca 5 NaN 6 caba 7 dog 8 cat dtype: object
六、合并
Pandas提供了大量的方法能够轻松的对Series,DataFrame和Panel对象进行各种符合各种逻辑关系的合并操作。具体请参阅: Merging section
l Concat
l Join 类似于SQL类型的合并,具体请参阅: Database style joining
l Append 将一行连接到一个DataFrame上,具体请参阅 Appending :
七、分组
对于”group by”操作,我们通常是指以下一个或多个操作步骤:
l (Splitting)按照一些规则将数据分为不同的组;
l (Applying)对于每组数据分别执行一个函数;
l (Combining)将结果组合到一个数据结构中;
详情请参阅: Grouping section
1、 分组并对每个分组执行sum函数:
2、 通过多个列进行分组形成一个层次索引,然后执行函数:
八、Reshaping
详情请参阅 Hierarchical Indexing 和 Reshaping 。
l Stack
In [95]: tuples = list(zip(*[['bar', 'bar', 'baz', 'baz', ....: 'foo', 'foo', 'qux', 'qux'], ....: ['one', 'two', 'one', 'two', ....: 'one', 'two', 'one', 'two']])) ....: In [96]: index = pd.MultiIndex.from_tuples(tuples, names=['first', 'second']) In [97]: df = pd.DataFrame(np.random.randn(8, 2), index=index, columns=['A', 'B']) In [98]: df2 = df[:4] In [99]: df2 Out[99]: A B first second bar one 0.029399 -0.542108 two 0.282696 -0.087302 baz one -1.575170 1.771208 two 0.816482 1.100230
In [102]: stacked.unstack() Out[102]: A B first second bar one 0.029399 -0.542108 two 0.282696 -0.087302 baz one -1.575170 1.771208 two 0.816482 1.100230 In [103]: stacked.unstack(1) Out[103]: second one two first bar A 0.029399 0.282696 B -0.542108 -0.087302 baz A -1.575170 0.816482 B 1.771208 1.100230 In [104]: stacked.unstack(0) Out[104]: first bar baz second one A 0.029399 -1.575170 B -0.542108 1.771208 two A 0.282696 0.816482 B -0.087302 1.100230
l 数据透视表,详情请参阅: Pivot Tables .
In [105]: df = pd.DataFrame({'A' : ['one', 'one', 'two', 'three'] * 3, .....: 'B' : ['A', 'B', 'C'] * 4, .....: 'C' : ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'] * 2, .....: 'D' : np.random.randn(12), .....: 'E' : np.random.randn(12)}) .....: In [106]: df Out[106]: A B C D E 0 one A foo 1.418757 -0.179666 1 one B foo -1.879024 1.291836 2 two C foo 0.536826 -0.009614 3 three A bar 1.006160 0.392149 4 one B bar -0.029716 0.264599 5 one C bar -1.146178 -0.057409 6 two A foo 0.100900 -1.425638 7 three B foo -1.035018 1.024098 8 one C foo 0.314665 -0.106062 9 one A bar -0.773723 1.824375 10 two B bar -1.170653 0.595974 11 three C bar 0.648740 1.167115
可以从这个数据中轻松的生成数据透视表:
九、时间序列
Pandas在对频率转换进行重新采样时拥有简单、强大且高效的功能(如将按秒采样的数据转换为按5分钟为单位进行采样的数据)。这种操作在金融领域非常常见。具体参考: Time Series section 。
1、 时区表示:
2、 时区转换:
3、 时间跨度转换:
4、 时期和时间戳之间的转换使得可以使用一些方便的算术函数。
十、Categorical
从0.15版本开始,pandas可以在DataFrame中支持Categorical类型的数据,详细 介绍参看: categorical introduction 和 API documentation 。
In [127]: df = pd.DataFrame({"id":[1,2,3,4,5,6], "raw_grade":['a', 'b', 'b', 'a', 'a', 'e']})
1、 将原始的grade转换为Categorical数据类型:
2、 将Categorical类型数据重命名为更有意义的名称:
3、 对类别进行重新排序,增加缺失的类别:
In [131]: df["grade"] = df["grade"].cat.set_categories(["very bad", "bad", "medium", "good", "very good"]) In [132]: df["grade"] Out[132]: 0 very good 1 good 2 good 3 very good 4 very good 5 very bad Name: grade, dtype: category Categories (5, object): [very bad, bad, medium, good, very good]
4、 排序是按照Categorical的顺序进行的而不是按照字典顺序进行:
5、 对Categorical列进行排序时存在空的类别:
十一、画图
具体文档参看: Plotting docs
In [135]: ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) In [136]: ts = ts.cumsum() In [137]: ts.plot() Out[137]: <matplotlib.axes._subplots.AxesSubplot at 0x7ff2ab2af550>
对于DataFrame来说,plot是一种将所有列及其标签进行绘制的简便方法:
十二、导入和保存数据
l CSV,参考: Writing to a csv file
1、 写入csv文件:
2、 从csv文件中读取:
In [142]: pd.read_csv('foo.csv') Out[142]: Unnamed: 0 A B C D 0 2000-01-01 0.266457 -0.399641 -0.219582 1.186860 1 2000-01-02 -1.170732 -0.345873 1.653061 -0.282953 2 2000-01-03 -1.734933 0.530468 2.060811 -0.515536 3 2000-01-04 -1.555121 1.452620 0.239859 -1.156896 4 2000-01-05 0.578117 0.511371 0.103552 -2.428202 5 2000-01-06 0.478344 0.449933 -0.741620 -1.962409 6 2000-01-07 1.235339 -0.091757 -1.543861 -1.084753 .. ... ... ... ... ... 993 2002-09-20 -10.628548 -9.153563 -7.883146 28.313940 994 2002-09-21 -10.390377 -8.727491 -6.399645 30.914107 995 2002-09-22 -8.985362 -8.485624 -4.669462 31.367740 996 2002-09-23 -9.558560 -8.781216 -4.499815 30.518439 997 2002-09-24 -9.902058 -9.340490 -4.386639 30.105593 998 2002-09-25 -10.216020 -9.480682 -3.933802 29.758560 999 2002-09-26 -11.856774 -10.671012 -3.216025 29.369368 [1000 rows x 5 columns]
l HDF5,参考: HDFStores
1、 写入HDF5存储:
In [143]: df.to_hdf('foo.h5','df')
2、 从HDF5存储中读取:
In [144]: pd.read_hdf('foo.h5','df') Out[144]: A B C D 2000-01-01 0.266457 -0.399641 -0.219582 1.186860 2000-01-02 -1.170732 -0.345873 1.653061 -0.282953 2000-01-03 -1.734933 0.530468 2.060811 -0.515536 2000-01-04 -1.555121 1.452620 0.239859 -1.156896 2000-01-05 0.578117 0.511371 0.103552 -2.428202 2000-01-06 0.478344 0.449933 -0.741620 -1.962409 2000-01-07 1.235339 -0.091757 -1.543861 -1.084753 ... ... ... ... ... 2002-09-20 -10.628548 -9.153563 -7.883146 28.313940 2002-09-21 -10.390377 -8.727491 -6.399645 30.914107 2002-09-22 -8.985362 -8.485624 -4.669462 31.367740 2002-09-23 -9.558560 -8.781216 -4.499815 30.518439 2002-09-24 -9.902058 -9.340490 -4.386639 30.105593 2002-09-25 -10.216020 -9.480682 -3.933802 29.758560 2002-09-26 -11.856774 -10.671012 -3.216025 29.369368 [1000 rows x 4 columns]
l Excel,参考: MS Excel
1、 写入excel文件:
In [145]: df.to_excel('foo.xlsx', sheet_name='Sheet1')
2、 从excel文件中读取:
In [146]: pd.read_excel('foo.xlsx', 'Sheet1', index_col=None, na_values=['NA']) Out[146]: A B C D 2000-01-01 0.266457 -0.399641 -0.219582 1.186860 2000-01-02 -1.170732 -0.345873 1.653061 -0.282953 2000-01-03 -1.734933 0.530468 2.060811 -0.515536 2000-01-04 -1.555121 1.452620 0.239859 -1.156896 2000-01-05 0.578117 0.511371 0.103552 -2.428202 2000-01-06 0.478344 0.449933 -0.741620 -1.962409 2000-01-07 1.235339 -0.091757 -1.543861 -1.084753 ... ... ... ... ... 2002-09-20 -10.628548 -9.153563 -7.883146 28.313940 2002-09-21 -10.390377 -8.727491 -6.399645 30.914107 2002-09-22 -8.985362 -8.485624 -4.669462 31.367740 2002-09-23 -9.558560 -8.781216 -4.499815 30.518439 2002-09-24 -9.902058 -9.340490 -4.386639 30.105593 2002-09-25 -10.216020 -9.480682 -3.933802 29.758560 2002-09-26 -11.856774 -10.671012 -3.216025 29.369368 [1000 rows x 4 columns]