Python使用Pandas库常见操作详解

这篇文章主要介绍了Python使用Pandas库常见操作,结合实例形式详细分析了Python Pandas模块的功能、原理、数据对象创建、查看、选择等相关操作技巧与注意事项,需要的朋友可以参考下

本文实例讲述了Python使用Pandas库常见操作。分享给大家供大家参考,具体如下:

1、概述

Pandas 是Python的核心数据分析支持库,提供了快速、灵活、明确的数据结构,旨在简单、直观地处理关系型、标记型数据。Pandas常用于处理带行列标签的矩阵数据、与 SQL 或 Excel 表类似的表格数据,应用于金融、统计、社会科学、工程等领域里的数据整理与清洗、数据分析与建模、数据可视化与制表等工作。

数据类型:Pandas 不改变原始的输入数据,而是复制数据生成新的对象,有普通对象构成的一维数组成为Series,由Series构成的二维数组表称为DataFrame,其行被称为index,列为Colum。

安装:如果使用anaconda集成环境则会自动安装numpy、scipy、pandas等数据科学包,也可以通过python包管理工具安装pandas:

 pip install pandas

2、数据对象的创建

通过Series()函数包裹一维数组可以创建Series对象,其中数组的元素可以是各种类型。

通过DataFrame()函数包裹二维数组可以创建一个DataFrame对象,可以通过参数index、columns指定行标签和列标签。也可以通过python的字典类型初始化DataFrame,其键名默认为列标签

 import pandas as pd import numpy as np # 通过一维数组初始化Series s = pd.Series([1, 2.0, np.nan, 'test']) print(s) # 通过二维数组初始化DataFrame arr = np.random.randn(6, 4) arr_df = pd.DataFrame(arr, index=np.arange(1, 7), columns=list('ABCD')) print(arr_df) # 通过字典dict初始化DataFrame dic = {'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"]) } dic_df = pd.DataFrame(dic) print(dic_df)

其运行结果如下:

 # Series数据 0    1 1    2 2   NaN 3  test dtype: object # 二维数组的DataFrame A     B     C     D 1 -0.085417 -0.816502 1.495134 -0.277742 2 1.657144 -0.203346 0.631930 -1.182239 3 -2.303923 -0.535696 1.315379 0.129682 4 0.133198 -0.239664 -2.004494 0.119965 5 -1.454717 2.114255 -0.538678 -0.580361 6 -0.759183 0.141554 -0.243270 2.840325 # dict字典DataFrame A     B  C D   E 0 1.0 2013-01-02 1.0 3  test 1 1.0 2013-01-02 1.0 3 train 2 1.0 2013-01-02 1.0 3  test 3 1.0 2013-01-02 1.0 3 train

3、查看数据

函数head(n)可以查看DataFrame前n行的数据,tail(n)查看倒数n行的数据

index()查看DataFrame的行标签,columns显示列标签

describe()按列显示数据的统计信息,包括计数、均值、方差、最小最大值等。

函数mean()显示所有列的均值,mean(1)显示所有行的均值

sum()求所有列的均值,sum(1)求所有行的均值

DataFrame有一个empty属性用于判断是否为空,若为空则返回True

 arr = np.random.randn(6, 4) df = pd.DataFrame(arr, index=np.arange(1, 7), columns=list('ABCD')) print(df.head(3)) print(df.index) print(df.describe())

结果如下

 # 查看前三行数据 A     B     C     D 1 3.260449 -0.619396 0.070877 1.586914 2 -0.529708 0.071917 -1.919316 1.845727 3 -1.005765 2.176579 -0.323483 -1.295067 # 查看行标签 Int64Index([1, 2, 3, 4, 5, 6], dtype='int64') # 查看统计信息 A     B     C     D count 6.000000 6.000000 6.000000 6.000000 mean -0.184606 -0.487184 0.079433 0.855810 std  1.721394 1.800460 1.379498 1.128764 min  -1.443635 -3.091446 -1.919316 -1.295067 25%  -0.967105 -1.430192 -0.281188 0.778729 50%  -0.694488 -0.273739 -0.041713 1.150944 75%  -0.531744 0.197755 0.355731 1.508475 max  3.260449 2.176579 2.352142 1.845727

4、数据的选择

可以直接通过DataFrame对象选取列或者行,

 # 选取一个列A,等价于df['A'] print(df.A) # 选取第1到第3行,行下标从0开始 print(df[1:3]) ''' # 标签为A的那一列 1  0.644427 2  0.643149 3  1.374668 4  -0.154465 5  -0.338085 6  -1.989284 Name: A, dtype: float64 # 第1~3行 A     B     C     D 2 0.643149 1.769001 -0.166028 -0.036854 3 1.374668 -0.118593 -0.202222 0.308353 '''

通过loc[]方法可以通过标签对DataFrame的一行、一列、几行几列或者是某个具体的值进行选择

 # 取出行标签为2的那一行 print(df.loc[2]) # 取出行标签为1~3,列标签为'A','B'的内容 print(df.loc[1:3, ['A', 'B']]) # 获取行标签为1,列标签为'A'的具体值,等价于df.at[1,'A'] print(df.loc[1, 'A']) ''' # 标签为2的一行 A  0.681469 B  -0.053046 C  -1.384877 D  -0.447700 Name: 2, dtype: float64 # 标签为1~3,列标签为'A','B'的内容 A     B 1 0.710907 -0.950896 2 0.681469 -0.053046 3 0.781981 0.123072 # 行标签为1,列标签为'A'的具体值 0.7109074858947351 '''

除了通过行列标签来进行取值以外,还可以通过行列的数组的位置进行取值,其方法名为iloc[]

 # 取出第一行,行下标从0开始 print(df.iloc[0]) # 显示第1,2,4行的第0,2列 print(df.iloc[[1, 2, 4], [0, 2]]) # 显示第1行第1列的具体值,等价于df.iat[1,1] print(df.iloc[1, 1])

还可以在选择时对数据进行过滤

 # 输出A那一列大于0的所有行 print(df[df.A > 0]) df['E'] = ['one', 'one', 'two', 'three', 'four', 'three'] # 输出E那一列存在two、four的所有行 print(df[df['E'].isin(['two', 'four'])]) ''' A     B     C     D 3 0.168998 -0.732362 -0.098542 0.413128 5 0.513677 -0.163231 -0.098037 -0.606693 A     B     C     D   E 3 0.168998 -0.732362 -0.098542 0.413128  two 5 0.513677 -0.163231 -0.098037 -0.606693 four '''

5、操作数据

通过insert()方法可以实现在指定位置插入一列,也可以直接将一个数组赋值给DataFrame,这将默认添加到最后一列

可以通过之前的选择方法loc、iloc找到指定的行列,然后直接赋值,如果该位置存在数据则会修改,否则添加

通过drop()方法删除指定的数据,index属性指定删除的行,columns指定删除的列,inplace属性是否在原数据集上操作,默认为False,此时需要一个变量来接收删除后的结果

 df = pd.DataFrame(data = [['lisa','f',22],['joy','f',22],['tom','m','21']], index = [1,2,3],columns = ['name','sex','age']) citys = ['ny','zz','xy'] #在第0列,加上column名称为city,值为citys的数值。 df.insert(0,'city',citys) jobs = ['student','AI','teacher'] # 默认在df最后一列加上column名称为job,值为jobs的数据。 df['job'] = jobs # 若df中没有index为“4”的这一行的话,则添加,否则修改 df.loc[4] = ['zz', 'mason', 'm', 24, 'engineer'] print(df) # 删除行标签为1的行 dp=df.drop(index=1) print(dp) # 在原数据集上删除列标签为sex的列 df.drop(columns=['sex'],inplace=True) print(df)

结果如下:

 # 添加后的数据 city  name sex age    job 1  ny  lisa  f 22  student 2  zz  joy  f 22    AI 3  xy  tom  m 21  teacher 4  zz mason  m 24 engineer # 删除第一行 city  name sex age    job 2  zz  joy  f 22    AI 3  xy  tom  m 21  teacher 4  zz mason  m 24 engineer # 删除sex列 city  name age    job 1  ny  lisa 22  student 2  zz  joy 22    AI 3  xy  tom 21  teacher 4  zz mason 24 engineer

对DataFrame进行转置操作,调用.T

sort_index(axis=1, ascending=False)对数据进行排序,axis=0代表按行标签排序,axis=1代表按列标签排序

sort_values(by='A')按某一列的值对数据进行排序,这里是按列标签为A的

apply()函数对DataFrame的每一行应用函数

 print(df.T) si=df.sort_index(axis=1, ascending=False) print(si) sv=df.sort_values(by='A') print(sv) # 应用匿名函数,用每一列最大值减去最小值 df.apply(lambda x: x.max() - x.min()) print(df) ''' # 数据转置 1     2     3     4     5     6 A -1.176180 -1.301768 0.907088 -1.528101 1.098978 -1.280193 B -0.461954 -0.749642 1.169118 -0.297765 0.531088 -0.999842 C -1.715094 -0.512856 0.511861 -0.247240 1.696772 -0.902995 D 1.336999 0.209091 2.254337 0.649625 -0.049886 -1.514815 # 按列标签倒序 D     C     B     A 1 1.336999 -1.715094 -0.461954 -1.176180 2 0.209091 -0.512856 -0.749642 -1.301768 3 2.254337 0.511861 1.169118 0.907088 4 0.649625 -0.247240 -0.297765 -1.528101 5 -0.049886 1.696772 0.531088 1.098978 6 -1.514815 -0.902995 -0.999842 -1.280193 # 按列A的值递增对行排序 A     B     C     D 4 -1.528101 -0.297765 -0.247240 0.649625 2 -1.301768 -0.749642 -0.512856 0.209091 6 -1.280193 -0.999842 -0.902995 -1.514815 1 -1.176180 -0.461954 -1.715094 1.336999 3 0.907088 1.169118 0.511861 2.254337 5 1.098978 0.531088 1.696772 -0.049886 # 函数的应用 A  2.073961 B  2.671590 C  1.785291 D  0.000000 F  4.000000 dtype: float64 '''

panda的concat函数可以将两个相同类型的DataFrame在行的维度上进行拼接

merge()函数可以将不同DataFrame按列拼接

append()函数可以在DataFrame的结尾追加

 # 将第一行和最后一行拼接 print(pd.concat([df[:1], df[-2:-1]])) # 将第4行追加到结尾 print(df.append(df.iloc[3])) # 将两个DataFrame按列拼接 df1 = pd.DataFrame({'row1': ['foo', 'bar'], 'row2': [1, 2]}) df2 = pd.DataFrame({'row1': ['foo', 'bar'], 'row3': [4, 5]}) print(pd.merge(df1, df2)) ''' # 按行拼接 A     B     C     D 1 -0.527221 -0.754650 -2.385270 -2.569586 5 0.054059 1.443911 -0.240856 -1.501045 # 追加 A     B     C     D 1 -0.527221 -0.754650 -2.385270 -2.569586 2 2.123332 -0.013431 -0.574359 -0.548838 3 -0.244057 -0.267805 1.089026 -0.022174 4 -0.789228 1.171906 0.526318 0.046655 5 0.054059 1.443911 -0.240856 -1.501045 6 0.756844 0.623305 -0.597299 0.034326 4 -0.789228 1.171906 0.526318 0.046655 # 按列拼接 row1 row2 row3 0 foo   1   4 1 bar   2   5 '''

groupby函数可以数据按列进行分组,分组后的结果可以使用for循环进行迭代,迭代中每个分组是一个(index,DataFrame)元组,可以对其中的DataFrame作进一步操作。

stack()可以将多列的数据压缩为两列显示

 df = pd.DataFrame({'A': ['foo', 'bar', 'foo', 'bar'], 'B': ['one', 'two', 'one', 'three'], 'C': np.random.randn(4), 'D': np.random.randn(4)}) # 按A、B两列进行分组 dg=df.groupby(['A', 'B']) for (index,df) in dg: print(df) # 压缩 print(df.stack()) ''' # 按列分组 A   B     C     D 3 bar three 0.802027 1.338614 A  B     C     D 1 bar two -0.567295 0.608978 A  B    C     D 0 foo one -0.17592 -0.191991 2 foo one -0.72258 0.711312 # 压缩为两列 0 A     foo B     one C   0.622471 D   0.10633 1 A     bar B     two C   0.065516 D  -0.844223 2 A     foo B     one C  0.0013226 D   -1.3328 3 A     bar B    three C  -0.678077 D   0.785117 dtype: object '''

Pandas主要使用值np.nan来表示缺失的数据。可以使用dropna(how='any')方法来删除所有存在空值的行,dropna(axis=1)删除存在空值的列。fillna(value=x)用指定值x填充所有的空值。

6、其他

通过pandas可以便捷地从其他格式文件进行转换

 # 将DataFrame写入csv文件 df.to_csv('foo.csv') # 从csv文件读数据 df = pd.read_csv('foo.csv') # excel文件的读写 df = pd.read_excel('foo.xlsx', 'Sheet1', index_col=None, na_values=['NA']) df.to_excel('foo.xlsx', sheet_name='Sheet1')

pandas提供了便捷的时间维度生成函数date_range(),第一个参数是起始时间,periods=生成的数量,freq=时间间隔,默认以天为单位

 # 从2019年1月1日开始,以秒为单位,生成五个时间 rng = pd.date_range('1/1/2019', periods=5, freq='S') ts = pd.Series(np.random.randint(0, 500, len(rng)), index=rng) print(ts) ''' 2019-01-01 00:00:01  161 2019-01-01 00:00:02  214 2019-01-01 00:00:03  110 2019-01-01 00:00:04  265 Freq: S, dtype: int32 '''

pandas结合matplot可以便捷地进行数据绘图

 ts = pd.Series(np.random.randint(0, 500, len(rng)), index=rng) # 将数据追加到一个数组统一显示 ts=ts.cumsum() # 调用matplot绘制图 ts.plot()

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

以上就是Python使用Pandas库常见操作详解的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » python