Python使用Pandas库常见操作详解


Posted in Python onJanuary 16, 2020

本文实例讲述了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代码检查工具pylint 让你的python更规范
Sep 05 Python
python中循环语句while用法实例
May 16 Python
python实现在字符串中查找子字符串的方法
Jul 11 Python
使用Python对微信好友进行数据分析
Jun 27 Python
Python设计模式之观察者模式原理与用法详解
Jan 16 Python
django项目用higcharts统计最近七天文章点击量
Aug 17 Python
关于numpy数组轴的使用详解
Dec 05 Python
简单了解python装饰器原理及使用方法
Dec 18 Python
nginx搭建基于python的web环境的实现步骤
Jan 03 Python
PyTorch-GPU加速实例
Jun 23 Python
Windows下Sqlmap环境安装教程详解
Aug 04 Python
python爬虫scrapy框架之增量式爬虫的示例代码
Feb 26 Python
Python 日期的转换及计算的具体使用详解
Jan 16 #Python
Python使用循环神经网络解决文本分类问题的方法详解
Jan 16 #Python
win10安装tesserocr配置 Python使用tesserocr识别字母数字验证码
Jan 16 #Python
Python通过VGG16模型实现图像风格转换操作详解
Jan 16 #Python
Python使用turtle库绘制小猪佩奇(实例代码)
Jan 16 #Python
PyCharm汉化安装及永久激活详细教程(靠谱)
Jan 16 #Python
python如何使用Redis构建分布式锁
Jan 16 #Python
You might like
php 变量定义方法
2009/06/14 PHP
浅谈php7的重大新特性
2015/10/23 PHP
一个完整的php文件上传类实例讲解
2015/10/27 PHP
php的api数据接口书写实例(推荐)
2016/09/22 PHP
thinkPHP自动验证、自动添加及表单错误问题分析
2016/10/17 PHP
判断用户的在线状态 onbeforeunload事件
2011/03/05 Javascript
JS动态增加删除UL节点LI及相关内容示例
2014/05/21 Javascript
jquery中post方法用法实例
2014/10/21 Javascript
五种js判断是否为整数类型方式
2015/12/03 Javascript
JS上传图片预览插件制作(兼容到IE6)
2016/08/07 Javascript
Bootstrap导航条的使用和理解3
2016/12/14 Javascript
JavaScript闭包和范围实例详解
2016/12/19 Javascript
JavaScript基础之this详解
2017/06/04 Javascript
Web制作验证码功能实例代码
2017/06/19 Javascript
axios进阶实践之利用最优雅的方式写ajax请求
2017/12/20 Javascript
值得收藏的八个常用的js正则表达式
2018/10/19 Javascript
Openlayers实现地图全屏显示
2020/09/28 Javascript
Chrome插件开发系列一:弹窗终结者开发实战
2020/10/02 Javascript
编写Python脚本来获取Google搜索结果的示例
2015/05/04 Python
在Python的Django框架中显示对象子集的方法
2015/07/21 Python
解决PyCharm的Python.exe已经停止工作的问题
2018/11/29 Python
python自动发送测试报告邮件功能的实现
2019/01/22 Python
Django文件存储 默认存储系统解析
2019/08/02 Python
Django Admin后台添加数据库视图过程解析
2020/04/01 Python
python调用API接口实现登陆短信验证
2020/05/10 Python
使用python实现名片管理系统
2020/06/18 Python
python Yaml、Json、Dict之间的转化
2020/10/19 Python
详解css3 object-fit属性
2018/07/27 HTML / CSS
html5移动端价格输入键盘的实现
2019/09/16 HTML / CSS
豪华复古化妆:Besame Cosmetics
2019/09/06 全球购物
德国购买踏板车网站:Microscooter
2019/10/14 全球购物
学生自我鉴定范文
2013/10/04 职场文书
经管应届生求职信
2013/11/17 职场文书
经济与贸易专业应届生求职信
2013/11/19 职场文书
2015年街道除四害工作总结
2015/05/15 职场文书
公务员岗前培训心得体会
2016/01/08 职场文书