python pandas库详解
来源:互联网 发布:网络用语小白什么意思 编辑:程序博客网 时间:2024/05/22 05:47
Series
基本特征:类似一维数组的对象,由数据和索引组成
相当于定长有序的字典,index和values相互独立
import pandas as pdfrom pandas import Seriesa=pd.Series([1,2.0,'a'])print(a)
0 1
1 2
2 a
dtype: object
自定义Series的index
>>> #指定Series的索引>>> b=pd.Series(['aa','bb','cc'],index=[1,2,3])>>> b1 aa2 bb3 ccdtype: object>>> b.indexInt64Index([1, 2, 3], dtype='int64')>>> b.valuesarray(['aa', 'bb', 'cc'], dtype=object)
Series的数据对齐功能
判断哪些索引值没有在字典里
>>> data={'aa':'92','bb':'99','cc':'96'}>>> sinindex=['aa','bb','cc','dd']>>> pd.Series(data,index=sinindex)aa 92bb 99cc 96dd NaNdtype: object>>> #判断哪些索引值是空的>>> pd.isnull(pd.Series(data,index=sinindex))aa Falsebb Falsecc Falsedd Truedtype: bool>>>
>>> #在算术运算中自动对齐不同索引的数据>>> aSer=pd.Series(data,index=sinindex)>>> aSeraa 92bb 99cc 96dd NaNdtype: object>>> bSer={'aa':'86','dd':'122','ee':'11'}>>> cSer=pd.Series(bSer)>>> aSer+cSeraa 9286bb NaNcc NaNdd NaNee NaNdtype: object
Series的name属性
Series对象和索引具有name属性
>>> aSeraa 92bb 99cc 96dd NaNdtype: object>>> aSer.name='winycg'>>> aSer.index.name='students'>>> aSerstudentsaa 92bb 99cc 96dd NaNName: winycg, dtype: object
DataFrame
基本特征:
(1)含有一个有序的列
(2)一个表格型的数据结构
(3)大致可看成一个共享index的Series集合
创建DataFrame
>>> #1.用字典>>> data={'name':['aa','bb','cc'],'pay':[4000,5000,6000]}>>> frame=pd.DataFrame(data)>>> frame name pay0 aa 40001 bb 50002 cc 6000>>> #上述索引为默认索引>>> import numpy as np>>> frame=pd.DataFrame(data,index=range(1,4),columns=['name','pay'])>>> frame name pay1 aa 40002 bb 50003 cc 6000>>> #索引>>> frame.indexRangeIndex(start=1, stop=4, step=1)>>> #字段名称>>> frame.columnsIndex(['name', 'pay'], dtype='object')>>> frame.valuesarray([['aa', '4000'], ['bb', '5000'], ['cc', '6000']], dtype=object)
>>> #2.使用数组array创建>>> import pandas as pd>>> df1=pd.DataFrame(np.arange(12).reshape((3,4)))>>> df1 0 1 2 30 0 1 2 31 4 5 6 72 8 9 10 11>>> #上述为默认索引值和字段名>>> df2=pd.DataFrame(np.arange(12).reshape((3,4)),index=np.arange(1,4),columns=['a','b','c','d'])>>> df2 a b c d1 0 1 2 32 4 5 6 73 8 9 10 11>>> #上述为指定索引和字段名
>>>#产生index为时间序列>>> dates=pd.date_range('20170520',periods=7)>>> datesDatetimeIndex(['2017-05-20', '2017-05-21', '2017-05-22', '2017-05-23', '2017-05-24', '2017-05-25', '2017-05-26'], dtype='datetime64[ns]', freq='D')>>> dates=pd.date_range('20170520',periods=3)>>> datesDatetimeIndex(['2017-05-20', '2017-05-21', '2017-05-22'], dtype='datetime64[ns]', freq='D')>>> df=pd.DataFrame(np.arange(12).reshape((3,4)),index=dates)>>> df 0 1 2 32017-05-20 0 1 2 32017-05-21 4 5 6 72017-05-22 8 9 10 11
取得DataFrame的行和列可以获得Series
>>> df a b c dx 0 1 2 3y 4 5 6 7z 8 9 10 11>>> #选择行,以下标的形式,只能是序列>>> df[:2] a b c dx 0 1 2 3y 4 5 6 7>>> df[0:1] a b c dx 0 1 2 3>>>#选择行,以标签名的形式,只能是序列,包含最后一个元素>>> df['x':'z'] a b c dx 0 1 2 3y 4 5 6 7z 8 9 10 11>>>#------------------------------------------------------------>>> #选择列,若是一列则类型为Series>>> df.ax 0y 4z 8Name: a, dtype: int32>>> df['a']x 0y 4z 8Name: a, dtype: int32>>> df[['a','b']] a bx 0 1y 4 5z 8 9>>>#------------------------------------------------------------->>>用标签选择:loc>>>#选择行>>> df.loc['x']a 0b 1c 2d 3Name: x, dtype: int32>>> type(df.loc['x'])<class 'pandas.core.series.Series'>>>#上述为Series类型>>>#选择行和列>>> df.loc[['x','y'],['a','b']] a bx 0 1y 4 5>>> type(df.loc[['x','y'],['a','b']])<class 'pandas.core.frame.DataFrame'>>>> df.loc['x',['a','b']]a 0b 1Name: x, dtype: int32>>> type(df.loc['x',['a','b']])<class 'pandas.core.series.Series'>>>>#------------------------------------------------------------->>>#用位置选择(和numpy的二维array切片操作类似):>>> df.iloc[1:3,2:4] c dy 6 7z 10 11>>> #间隔行输出>>> df.iloc[[0,2],2]x 2z 10Name: c, dtype: int32>>> df.iloc[:,1]x 1y 5z 9Name: b, dtype: int32>>> df.iloc[1,:]a 4b 5c 6d 7Name: y, dtype: int32>>> df.iloc[1,1]5>>>#------------------------------------------------------------->>> #混合标签和位置:ix>>>#选择行,可以转化为Series格式>>> df.ix[1]a 4b 5c 6d 7Name: y, dtype: int32>>> df.ix[:2,['a','b']] a bx 0 1y 4 5>>> df.ix[1:2] a b c dy 4 5 6 7>>>#-------------------------------------------------------------->>>使用布尔参数>>> df>5 a b c dx False False False Falsey False False True Truez True True True True>>> df[df>5]=99>>> df a b c dx 0 1 2 3y 4 5 99 99z 99 99 99 99
DataFrame对象的添加、删除和修改
>>> dff a b c d1 0 1 2 32 4 5 6 73 8 9 10 11>>>#修改某一列>>> dff['a']=5>>> dff a b c d1 5 1 2 32 5 5 6 73 5 9 10 11>>> #添加某个列>>> data=[2,3,10]>>> dff['e']=data>>> dff a b c e1 5 1 2 22 5 5 6 33 5 9 10 10>>> #删除某个列>>> del dff['d']>>> dff a b c1 5 1 22 5 5 63 5 9 10
DataFrame的排序功能
>>> df2 a b c d1 0 1 2 32 4 5 6 73 8 9 10 11>>> df2.sort_index(axis=1,ascending=False) d c b a1 3 2 1 02 7 6 5 43 11 10 9 8>>> #对columns进行排序>>> df2.sort_index(axis=0,ascending=False) a b c d3 8 9 10 112 4 5 6 71 0 1 2 3>>> #对index进行排序>>> df2.sort_values(by='b') a b c d1 0 1 2 32 4 5 6 73 8 9 10 11>>> #对b列的数据进行排序
DataFrame统计和筛选
>>> df a b c d1 0 1 2 32 4 5 6 73 8 9 10 11>>> #找寻最小值>>> df.a.min()0>>>#求列的平均值>>> df.a.mean()4.0>>>#----------------------------------------------->>> #选择符合条件的行>>> df[df.a>=4] a b c d2 4 5 6 73 8 9 10 11>>>#找寻index在(1,3)之间的行>>> df[(df.index>1) & (df.index<3)] a b c d2 4 5 6 7
Grouping分组
>>> df=pd.DataFrame({'a':[1,2,2,3,3,4],'b':[2,3,4,4,1,4],'c':[2,3,2,2,3,8]})>>> df a b c0 1 2 21 2 3 32 2 4 23 3 4 24 3 1 35 4 4 8>>>#按照某一列进行分组,显示每个组内行的个数>>> df.groupby('a').count() b ca 1 1 12 2 23 2 24 1 1>>> df.groupby('b').count() a cb 1 1 12 1 13 1 14 3 3>>>#---------------------------------------------------------->>> #对组内的每一列求和>>> df.groupby('a').sum() b ca 1 2 22 7 53 5 54 4 8>>> #显示组内某一列的和>>> df.groupby('a').b.sum()a1 22 73 54 4Name: b, dtype: int64
合并
方法1:Append
>>> df a b c0 1 2 21 2 3 32 2 4 23 3 4 24 3 1 35 4 4 8>>> dfx=pd.DataFrame(np.arange(6).reshape((2,3)),columns=['a','b','c'])>>> dfx a b c0 0 1 21 3 4 5>>>#合并DataFrame>>> df.append(dfx) a b c0 1 2 21 2 3 32 2 4 23 3 4 24 3 1 35 4 4 80 0 1 21 3 4 5>>> dfx=pd.DataFrame(np.arange(6).reshape((2,3)),columns=['Q','b','c'])>>> df.append(dfx) Q a b c0 NaN 1.0 2 21 NaN 2.0 3 32 NaN 2.0 4 23 NaN 3.0 4 24 NaN 3.0 1 35 NaN 4.0 4 80 0.0 NaN 1 21 3.0 NaN 4 5
方法2.concat
>>> df=pd.DataFrame(np.arange(12).reshape((3,4)),index=[1,2,3],columns=['a','b','c','d'])>>> df a b c d1 0 1 2 32 4 5 6 73 8 9 10 11>>> dfx=pd.DataFrame({'d':[3,7,6],'e':[1,2,3]})>>> dfx d e0 3 11 7 22 6 3>>>#------------------------------------------------------->>>#上下合并>>> pd.concat([df,dfx]) a b c d e1 0.0 1.0 2.0 3 NaN2 4.0 5.0 6.0 7 NaN3 8.0 9.0 10.0 11 NaN0 NaN NaN NaN 3 1.01 NaN NaN NaN 7 2.02 NaN NaN NaN 6 3.0>>>#重新设置默认坐标>>> pd.concat([df,dfx],ignore_index=True) a b c d e0 0.0 1.0 2.0 3 NaN1 4.0 5.0 6.0 7 NaN2 8.0 9.0 10.0 11 NaN3 NaN NaN NaN 3 1.04 NaN NaN NaN 7 2.0>>>#内连接,只连接公共的列>>> pd.concat([df,dfx],join='inner') d1 32 73 110 31 72 6>>>#--------------------------------------------------------->>>#左右合并>>> pd.concat([df,dfx],axis=1) a b c d d e0 NaN NaN NaN NaN 3.0 1.01 0.0 1.0 2.0 3.0 7.0 2.02 4.0 5.0 6.0 7.0 6.0 3.03 8.0 9.0 10.0 11.0 NaN NaN>>>#内连接,只连接公共的index>>> pd.concat([df,dfx],axis=1,join='inner') a b c d d e1 0 1 2 3 7 22 4 5 6 7 6 3>>>#---------------------------------------------------------->>>#指定在某些轴进行索引>>> pd.concat([df,dfx],axis=1,join_axes=[df.index]) a b c d d e1 0 1 2 3 7.0 2.02 4 5 6 7 6.0 3.03 8 9 10 11 NaN NaN
方法3.类似于数据库中的连接
>>> df1=pd.DataFrame({'key':['a','b','c','e'],'data1':range(4)})>>> df1 data1 key0 0 a1 1 b2 2 c3 3 e>>> df2=pd.DataFrame({'key':['a','b','d'],'data2':range(3)})>>> df2 data2 key0 0 a1 1 b2 2 d>>>#------------------------------------------------------------>>>#df1和df2根据key进行内连接>>> pd.merge(df1,df2,on='key') data1 key data20 0 a 01 1 b 1>>>#若要连接的列名不同,可以显式指定>>> df3=pd.DataFrame({'key3':['a','b','c','e'],'data1':range(4)})>>> df3 data1 key30 0 a1 1 b2 2 c3 3 e>>> df4=pd.DataFrame({'key4':['a','b','d'],'data2':range(3)})>>> df4 data2 key40 0 a1 1 b2 2 d>>> pd.merge(df3,df4,left_on='key3',right_on='key4') data1 key3 data2 key40 0 a 0 a1 1 b 1 b>>>#----------------------------------------------------------->>>#外连接>>> pd.merge(df1,df2,on='key',how='outer') data1 key data20 0.0 a 0.01 1.0 b 1.02 2.0 c NaN3 3.0 e NaN4 NaN d 2.0>>>#显示连接的情况>>> pd.merge(df1,df2,on='key',how='outer',indicator=True) data1 key data2 _merge0 0.0 a 0.0 both1 1.0 b 1.0 both2 2.0 c NaN left_only3 3.0 e NaN left_only4 NaN d 2.0 right_only>>>#----------------------------------------------------------->>>#利用多个键进行合并>>> left_df=pd.DataFrame({'key1':['a','b','c'],'key2':['d','e','f'],'lval':[1,2,3]})>>> left_df key1 key2 lval0 a d 11 b e 22 c f 3>>> right_df=pd.DataFrame({'key1':['a','r','c'],'key2':['d','e','f'],'rval':[4,5,6]})>>> right_df key1 key2 rval0 a d 41 r e 52 c f 6>>> pd.merge(left_df,right_df,on=['key1','key2']) key1 key2 lval rval0 a d 1 41 c f 3 6>>> pd.merge(left_df,right_df,on=['key1','key2'],how='outer') key1 key2 lval rval0 a d 1.0 4.01 b e 2.0 NaN2 c f 3.0 6.03 r e NaN 5.0>>>#----------------------------------------------------------
处理缺失数据
>>> dates=pd.date_range('20171101',periods=4)>>> df=pd.DataFrame(np.arange(12).reshape((4,3)),index=dates,columns=['a','b','c'])>>> df a b c2017-11-01 0 1 22017-11-02 3 4 52017-11-03 6 7 82017-11-04 9 10 11>>> df.iloc[0,1]=np.nan>>> df.iloc[1,2]=np.nan>>> df a b c2017-11-01 0 NaN 2.02017-11-02 3 4.0 NaN2017-11-03 6 7.0 8.02017-11-04 9 10.0 11.0>>>#----------------------------------------------------------->>>#去除存在nan的行>>> df.dropna() a b c2017-11-03 6 7.0 8.02017-11-04 9 10.0 11.0>>>#去除存在nan的列>>> df.dropna(axis=1) a2017-11-01 02017-11-02 32017-11-03 62017-11-04 9>>>#去除全为nan的行>>> df.dropna(how='all') a b c2017-11-01 0 NaN 2.02017-11-02 3 4.0 NaN2017-11-03 6 7.0 8.02017-11-04 9 10.0 11.0>>>#------------------------------------------------------------>>>#填充缺失数据>>> dfx=df.copy()>>> dfx.fillna(value=0.0) a b c2017-11-01 0 0.0 2.02017-11-02 3 4.0 0.02017-11-03 6 7.0 8.02017-11-04 9 10.0 11.0>>>#------------------------------------------------------------->>>#判断数据是否缺失>>> df.isnull() a b c2017-11-01 False True False2017-11-02 False False True2017-11-03 False False False2017-11-04 False False False>>>#判断DataFrame是否存在数据缺失>>> np.any(df.isnull())==TrueTrue>>> np.all(df.isnull())==TrueFalse
pandas的绘图功能
pandas主要是基于Series和DataFrame的数据进行绘图
绘制一列数据:
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltdf=pd.DataFrame(np.arange(12).reshape((3,4)),index=[1,2,3],columns=['a','b','c','d'])print(df)''' a b c d1 0 1 2 32 4 5 6 73 8 9 10 11'''df.b.plot()plt.show()
绘制柱形图:
df=pd.DataFrame(np.arange(12).reshape((3,4)),index=[1,2,3],columns=['a','b','c','d'])print(df)''' a b c d1 0 1 2 32 4 5 6 73 8 9 10 11'''df.plot(kind='bar')#绘制横向的柱形图df.plot(kind='barh')#产生堆积效果的柱状图df.plot(kind='bar',stacked=True)plt.show()
绘制饼状图
df.b.plot(kind='pie',autopct='%.2f')plt.show()
将DataFrame数据存取到csv格式的文件
>>> df=pd.DataFrame(np.arange(12).reshape((3,4)),index=[1,2,3],columns=['a','b','c','d'])>>> df a b c d1 0 1 2 32 4 5 6 73 8 9 10 11>>>#将df存入csv文件>>>df.to_csv('df.csv')>>>#忽略行标签(index),忽略列标签(header)>>> df.to_csv('df.csv',index=False)>>>#将csv文件中的DataFrame读取>>>pd.read_csv('df.csv') a b c d0 0 1 2 31 4 5 6 72 8 9 10 11
存取到excel格式文件
>>> df a b c d1 0 1 2 32 4 5 6 73 8 9 10 11>>> df.to_excel('df.xlsx',sheet_name='df1')>>> pd.read_excel('df.xlsx') a b c d1 0 1 2 32 4 5 6 73 8 9 10 11
阅读全文
0 0
- python pandas库详解
- python pandas详解
- python 之 pandas 详解
- python pandas.read_csv参数详解
- python pandas.read_csv参数详解
- python pandas库基础
- Python 中的Pandas库
- Python之Pandas库
- Python 中的Pandas库
- Python pandas库
- Python之Pandas库
- python之pandas库
- Python-Pandas(5)核心数据结构Series详解
- python pandas库具体用法
- python Pandas库-文件读取
- python——pandas库
- python pandas
- python-pandas
- C++构建循环链表(无头节点)
- 树链剖分初步
- [微机原理]BCD码减法
- 判断是否为微信内置浏览器
- NKOJ训练赛 过路费(最短路)
- python pandas库详解
- Angular模板与表达式的绑定
- BZOJ1066: [SCOI2007]蜥蜴
- java工程师简历的潜规则你知道吗?
- 基于 Agent 的模型入门Python实现 读书笔记
- java-序列化与反序列化
- XRecyclerView下拉刷新,加载更多,添加头布局
- 编写高质量代码 —— 异常退出条件的判断
- new和delete操作