十分钟搞定pandas
来源:互联网 发布:网站源码有什么用 编辑:程序博客网 时间:2024/05/23 05:07
本文是对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]: datesOut[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]: dfOut[9]: A B C D2013-01-01 0.469112 -0.282863 -1.509059 -1.1356322013-01-02 1.212112 -0.173215 0.119209 -1.0442362013-01-03 -0.861849 -2.104569 -0.494929 1.0718042013-01-04 0.721555 -0.706771 -1.039575 0.2718602013-01-05 -0.424972 0.567020 0.276232 -1.0874012013-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]: df2Out[11]: A B C D E F0 1.0 2013-01-02 1.0 3 test foo1 1.0 2013-01-02 1.0 3 train foo2 1.0 2013-01-02 1.0 3 test foo3 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]: s1Out[46]: 2013-01-02 12013-01-03 22013-01-04 32013-01-05 42013-01-06 52013-01-07 6Freq: D, dtype: int64In [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'] = 1In [57]: df1Out[57]: A B C D F E2013-01-01 0.000000 0.000000 -1.509059 5 NaN 1.02013-01-02 1.212112 -0.173215 0.119209 5 1.0 1.02013-01-03 -0.861849 -2.104569 -0.494929 5 2.0 NaN2013-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 a1 b2 c3 aaba4 baca5 NaN6 caba7 dog8 catdtype: 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]: df2Out[99]: A Bfirst second bar one 0.029399 -0.542108 two 0.282696 -0.087302baz one -1.575170 1.771208 two 0.816482 1.100230
In [102]: stacked.unstack()Out[102]: A Bfirst second bar one 0.029399 -0.542108 two 0.282696 -0.087302baz one -1.575170 1.771208 two 0.816482 1.100230In [103]: stacked.unstack(1)Out[103]: second one twofirst bar A 0.029399 0.282696 B -0.542108 -0.087302baz A -1.575170 0.816482 B 1.771208 1.100230In [104]: stacked.unstack(0)Out[104]: first bar bazsecond one A 0.029399 -1.575170 B -0.542108 1.771208two 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]: dfOut[106]: A B C D E0 one A foo 1.418757 -0.1796661 one B foo -1.879024 1.2918362 two C foo 0.536826 -0.0096143 three A bar 1.006160 0.3921494 one B bar -0.029716 0.2645995 one C bar -1.146178 -0.0574096 two A foo 0.100900 -1.4256387 three B foo -1.035018 1.0240988 one C foo 0.314665 -0.1060629 one A bar -0.773723 1.82437510 two B bar -1.170653 0.59597411 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 good1 good2 good3 very good4 very good5 very badName: grade, dtype: categoryCategories (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 D0 2000-01-01 0.266457 -0.399641 -0.219582 1.1868601 2000-01-02 -1.170732 -0.345873 1.653061 -0.2829532 2000-01-03 -1.734933 0.530468 2.060811 -0.5155363 2000-01-04 -1.555121 1.452620 0.239859 -1.1568964 2000-01-05 0.578117 0.511371 0.103552 -2.4282025 2000-01-06 0.478344 0.449933 -0.741620 -1.9624096 2000-01-07 1.235339 -0.091757 -1.543861 -1.084753.. ... ... ... ... ...993 2002-09-20 -10.628548 -9.153563 -7.883146 28.313940994 2002-09-21 -10.390377 -8.727491 -6.399645 30.914107995 2002-09-22 -8.985362 -8.485624 -4.669462 31.367740996 2002-09-23 -9.558560 -8.781216 -4.499815 30.518439997 2002-09-24 -9.902058 -9.340490 -4.386639 30.105593998 2002-09-25 -10.216020 -9.480682 -3.933802 29.758560999 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 D2000-01-01 0.266457 -0.399641 -0.219582 1.1868602000-01-02 -1.170732 -0.345873 1.653061 -0.2829532000-01-03 -1.734933 0.530468 2.060811 -0.5155362000-01-04 -1.555121 1.452620 0.239859 -1.1568962000-01-05 0.578117 0.511371 0.103552 -2.4282022000-01-06 0.478344 0.449933 -0.741620 -1.9624092000-01-07 1.235339 -0.091757 -1.543861 -1.084753... ... ... ... ...2002-09-20 -10.628548 -9.153563 -7.883146 28.3139402002-09-21 -10.390377 -8.727491 -6.399645 30.9141072002-09-22 -8.985362 -8.485624 -4.669462 31.3677402002-09-23 -9.558560 -8.781216 -4.499815 30.5184392002-09-24 -9.902058 -9.340490 -4.386639 30.1055932002-09-25 -10.216020 -9.480682 -3.933802 29.7585602002-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 D2000-01-01 0.266457 -0.399641 -0.219582 1.1868602000-01-02 -1.170732 -0.345873 1.653061 -0.2829532000-01-03 -1.734933 0.530468 2.060811 -0.5155362000-01-04 -1.555121 1.452620 0.239859 -1.1568962000-01-05 0.578117 0.511371 0.103552 -2.4282022000-01-06 0.478344 0.449933 -0.741620 -1.9624092000-01-07 1.235339 -0.091757 -1.543861 -1.084753... ... ... ... ...2002-09-20 -10.628548 -9.153563 -7.883146 28.3139402002-09-21 -10.390377 -8.727491 -6.399645 30.9141072002-09-22 -8.985362 -8.485624 -4.669462 31.3677402002-09-23 -9.558560 -8.781216 -4.499815 30.5184392002-09-24 -9.902058 -9.340490 -4.386639 30.1055932002-09-25 -10.216020 -9.480682 -3.933802 29.7585602002-09-26 -11.856774 -10.671012 -3.216025 29.369368[1000 rows x 4 columns]
- 十分钟搞定pandas
- 十分钟搞定pandas
- 十分钟搞定pandas
- 十分钟搞定pandas
- 十分钟搞定pandas
- 十分钟搞定pandas
- 十分钟搞定pandas
- 十分钟搞定pandas
- 十分钟搞定pandas
- 十分钟搞定pandas
- 十分钟搞定pandas
- 十分钟搞定pandas
- 十分钟搞定pandas
- 十分钟搞定pandas
- 十分钟搞定pandas
- 十分钟搞定pandas
- 十分钟搞定pandas
- 十分钟搞定pandas
- jQuery
- CDOJ 1294 天行廖的游戏 dp 容斥
- java基础二 java语言基础
- osx java ndk cocos 环境变量的配置
- 学习正则表达式
- 十分钟搞定pandas
- 119-epoll(触发模式)
- 软件测试的基础理论
- mysql workbench中PK,NN,UQ,BIN,UN,ZF,AI字段类型标识说明
- Qt Graphics入门小例以及实现场景中相关项拖拽功能总结.
- 学习记录
- 记一次openstack的部署过程
- Transfer-Encoding:chunked 返回数据过长导致中文乱码
- UVA 10048 Flyod算法