关键词:
【回炉重造】Python之Pandas详细教程
前言
为什么要学习Pandas?
那么问题来了:
numpy已经能够帮助我们处理数据,能够结合matplotlib解决我们数据分析的问题,那么pandas学习的目的在什么地方呢?
numpy能够帮我们处理处理数值型数据,但是这还不够, 很多时候,我们的数据除了数值之外,还有字符串,还有时间序列等
比如:我们通过爬虫获取到了存储在数据库中的数据
所以,pandas出现了。
什么是Pandas?
Pandas的名称来自于面板数据(panel data)
Pandas是一个强大的分析结构化数据的工具集,基于NumPy构建,提供了高级数据结构和数据操作工具,它是使Python成为强大而高效的数据分析环境的重要因素之一。
-
一个强大的分析和操作大型结构化数据集所需的工具集
-
基础是NumPy,提供了高性能矩阵的运算
-
提供了大量能够快速便捷地处理数据的函数和方法
-
应用于数据挖掘,数据分析
-
提供数据清洗功能
官网
1. Pandas的索引操作
索引对象Index
1. Series和DataFrame中的索引都是Index对象
示例代码:
print(type(ser_obj.index))
print(type(df_obj2.index))
print(df_obj2.index)
运行结果:
<class 'pandas.indexes.range.RangeIndex'>
<class 'pandas.indexes.numeric.Int64Index'>
Int64Index([0, 1, 2, 3], dtype='int64')
2. 索引对象不可变,保证了数据的安全
示例代码:
# 索引对象不可变
df_obj2.index[0] = 2
运行结果:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-23-7f40a356d7d1> in <module>()
1 # 索引对象不可变
----> 2 df_obj2.index[0] = 2
/Users/Power/anaconda/lib/python3.6/site-packages/pandas/indexes/base.py in __setitem__(self, key, value)
1402
1403 def __setitem__(self, key, value):
-> 1404 raise TypeError("Index does not support mutable operations")
1405
1406 def __getitem__(self, key):
TypeError: Index does not support mutable operations
3. 常见的Index种类
- Index,索引
- Int64Index,整数索引
- MultiIndex,层级索引
- DatetimeIndex,时间戳类型
3.1 Series索引
1. index 指定行索引名
示例代码:
ser_obj = pd.Series(range(5), index = ['a', 'b', 'c', 'd', 'e'])
print(ser_obj.head())
运行结果:
a 0
b 1
c 2
d 3
e 4
dtype: int64
2. 行索引
ser_obj[‘label’], ser_obj[pos]
示例代码:
# 行索引
print(ser_obj['b'])
print(ser_obj[2])
运行结果:
1
2
3. 切片索引
ser_obj[2:4], ser_obj[‘label1’: ’label3’]
注意,按索引名切片操作时,是包含终止索引的。
示例代码:
# 切片索引
print(ser_obj[1:3])
print(ser_obj['b':'d'])
运行结果:
b 1
c 2
dtype: int64
b 1
c 2
d 3
dtype: int64
4. 不连续索引
ser_obj[[‘label1’, ’label2’, ‘label3’]]
示例代码:
# 不连续索引
print(ser_obj[[0, 2, 4]])
print(ser_obj[['a', 'e']])
运行结果:
a 0
c 2
e 4
dtype: int64
a 0
e 4
dtype: int64
5. 布尔索引
示例代码:
# 布尔索引
ser_bool = ser_obj > 2
print(ser_bool)
print(ser_obj[ser_bool])
print(ser_obj[ser_obj > 2])
运行结果:
a False
b False
c False
d True
e True
dtype: bool
d 3
e 4
dtype: int64
d 3
e 4
dtype: int64
3.2 DataFrame索引
1. columns 指定列索引名
示例代码:
import numpy as np
df_obj = pd.DataFrame(np.random.randn(5,4), columns = ['a', 'b', 'c', 'd'])
print(df_obj.head())
运行结果:
a b c d
0 -0.241678 0.621589 0.843546 -0.383105
1 -0.526918 -0.485325 1.124420 -0.653144
2 -1.074163 0.939324 -0.309822 -0.209149
3 -0.716816 1.844654 -2.123637 -1.323484
4 0.368212 -0.910324 0.064703 0.486016
2. 列索引
df_obj[[‘label’]]
示例代码:
# 列索引
print(df_obj['a']) # 返回Series类型
运行结果:
0 -0.241678
1 -0.526918
2 -1.074163
3 -0.716816
4 0.368212
Name: a, dtype: float64
3. 不连续索引
df_obj[[‘label1’, ‘label2’]]
示例代码:
# 不连续索引
print(df_obj[['a','c']])
运行结果:
a c
0 -0.241678 0.843546
1 -0.526918 1.124420
2 -1.074163 -0.309822
3 -0.716816 -2.123637
4 0.368212 0.064703
4. 高级索引:标签、位置和混合
Pandas的高级索引有3种
1. loc 标签索引
DataFrame 不能直接切片,可以通过loc来做切片
loc是基于标签名的索引,也就是我们自定义的索引名
示例代码:
# 标签索引 loc
# Series
print(ser_obj['b':'d'])
print(ser_obj.loc['b':'d'])
# DataFrame
print(df_obj['a'])
# 第一个参数索引行,第二个参数是列
print(df_obj.loc[0:2, 'a'])
运行结果:
b 1
c 2
d 3
dtype: int64
b 1
c 2
d 3
dtype: int64
0 -0.241678
1 -0.526918
2 -1.074163
3 -0.716816
4 0.368212
Name: a, dtype: float64
0 -0.241678
1 -0.526918
2 -1.074163
Name: a, dtype: float64
2. iloc 位置索引
作用和loc一样,不过是基于索引编号来索引
示例代码:
# 整型位置索引 iloc
# Series
print(ser_obj[1:3])
print(ser_obj.iloc[1:3])
# DataFrame
print(df_obj.iloc[0:2, 0]) # 注意和df_obj.loc[0:2, 'a']的区别
运行结果:
b 1
c 2
dtype: int64
b 1
c 2
dtype: int64
0 -0.241678
1 -0.526918
Name: a, dtype: float64
3. ix 标签与位置混合索引
ix是以上二者的综合,既可以使用索引编号,又可以使用自定义索引,要视情况不同来使用,
如果索引既有数字又有英文,那么这种方式是不建议使用的,容易导致定位的混乱。
示例代码:
# 混合索引 ix
# Series
print(ser_obj.ix[1:3])
print(ser_obj.ix['b':'c'])
# DataFrame
print(df_obj.loc[0:2, 'a'])
print(df_obj.ix[0:2, 0])
运行结果:
b 1
c 2
dtype: int64
b 1
c 2
dtype: int64
0 -0.241678
1 -0.526918
2 -1.074163
Name: a, dtype: float64
注意
DataFrame索引操作,可将其看作ndarray的索引操作
标签的切片索引是包含末尾位置的
2. Pandas的对齐运算
Pandas的对齐运算是数据清洗的重要过程,可以按索引对齐进行运算,如果没对齐的位置则补NaN,最后也可以填充NaN
2.1 Series的对齐运算
1. Series 按行、索引对齐
示例代码:
s1 = pd.Series(range(10, 20), index = range(10))
s2 = pd.Series(range(20, 25), index = range(5))
print('s1: ' )
print(s1)
print('')
print('s2: ')
print(s2)
运行结果:
s1:
0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
dtype: int64
s2:
0 20
1 21
2 22
3 23
4 24
dtype: int64
2. Series的对齐运算
示例代码:
# Series 对齐运算
s1 + s2
运行结果:
0 30.0
1 32.0
2 34.0
3 36.0
4 38.0
5 NaN
6 NaN
7 NaN
8 NaN
9 NaN
dtype: float64
2.2 DataFrame的对齐运算
1. DataFrame按行、列索引对齐
示例代码:
df1 = pd.DataFrame(np.ones((2,2)), columns = ['a', 'b'])
df2 = pd.DataFrame(np.ones((3,3)), columns = ['a', 'b', 'c'])
print('df1: ')
print(df1)
print('')
print('df2: ')
print(df2)
运行结果:
df1:
a b
0 1.0 1.0
1 1.0 1.0
df2:
a b c
0 1.0 1.0 1.0
1 1.0 1.0 1.0
2 1.0 1.0 1.0
2. DataFrame的对齐运算
示例代码:
# DataFrame对齐操作
df1 + df2
运行结果:
a b c
0 2.0 2.0 NaN
1 2.0 2.0 NaN
2 NaN NaN NaN
2.3 填充未对齐的数据进行运算
fill_value
使用
add
,sub
,div
,mul
的同时,通过
fill_value
指定填充值,未对齐的数据将和填充值做运算
示例代码:
print(s1)
print(s2)
s1.add(s2, fill_value = -1)
print(df1)
print(df2)
df1.sub(df2, fill_value = 2.)
运行结果:
# print(s1)
0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
dtype: int64
# print(s2)
0 20
1 21
2 22
3 23
4 24
dtype: int64
# s1.add(s2, fill_value = -1)
0 30.0
1 32.0
2 34.0
3 36.0
4 38.0
5 14.0
6 15.0
7 16.0
8 17.0
9 18.0
dtype: float64
# print(df1)
a b
0 1.0 1.0
1 1.0 1.0
# print(df2)
a b c
0 1.0 1.0 1.0
1 1.0 1.0 1.0
2 1.0 1.0 1.0
# df1.sub(df2, fill_value = 2.)
a b c
0 0.0 0.0 1.0
1 0.0 0.0 1.0
2 1.0 1.0 1.0
算术方法表:
方法 | 描述 |
---|---|
add,radd | 加法(+) |
sub,rsub | 减法(-) |
div,rdiv | 除法(/) |
floordiv,rfllordiv | 整除(//) |
mul,rmul | 乘法(*) |
pow,rpow | 幂次方(**) |
3. Pandas的函数应用
3.1 apply 和 applymap
1. 可直接使用NumPy的函数
示例代码:
# Numpy ufunc 函数
df = pd.DataFrame(np.random.randn(5,4) - 1)
print(df)
print(np.abs(df))
运行结果:
0 1 2 3
0 -0.062413 0.844813 -1.853721 -1.980717
1 -0.539628 -1.975173 -0.856597 -2.612406
2 -1.277081 -1.088457 -0.152189 0.530325
3 -1.356578 -1.996441 0.368822 -2.211478
4 -0.562777 0.518648 -2.007223 0.059411
0 1 2 3
0 0.062413 0.844813 1.853721 1.980717
1 0.539628 1.975173 0.856597 2.612406
2 1.277081 1.088457 0.152189 0.530325
3 1.356578 1.996441 0.368822 2.211478
4 0.562777 0.518648 2.007223 0.059411
2. 通过apply将函数应用到列或行上
示例代码:
# 使用apply应用行或列数据
#f = lambda x : x.max()
print(df.apply(lambda x : x.max()))
运行结果:
0 -0.062413
1 0.844813
2 0.368822
3 0.530325
dtype: float64
注意指定轴的方向,默认axis=0,方向是列
示例代码:
# 指定轴方向,axis=1,方向是行
print(df.apply(lambda x : x.max(), axis=1))
运行结果:
0 0.844813
1 -0.539628
2 0.530325
3 0.368822
4 0.518648
dtype: float64
3. 通过applymap将函数应用到每个数据上
示例代码:
# 使用applymap应用到每个数据
f2 = lambda x : '%.2f' % x
print(df.applymap(f2))
运行结果:
0 1 2 3
0 -0.06 0.84 -1.85 -1.98
1 -0.54 -1.98 -0.86 -2.61
2 -1.28 -1.09 -0.15 0.53
3 -1.36 -2.00 0.37 -2.21
4 -0.56 0.52 -2.01 0.06
3.2 排序
1. 索引排序
sort_index()
排序默认使用升序排序,ascending=False 为降序排序
示例代码:
# Series
s4 = pd.Series(range(10, 15), index = np.random.randint(5, size=5))
print(s4)
# 索引排序
s4.sort_index() # 0 0 1 3 3
运行结果:
0 10
3 11
1 12
3 13
0 14
dtype: int64
0 10
0 14
1 12
3 11
3 13
dtype: int64
对DataFrame操作时注意轴方向
示例代码:
# DataFrame
df4 = pd.DataFrame(np.random.randn(3, 5),
index=np.random.randint(3, size=3),
columns=np.random.randint(5, size=5))
print(df4)
df4_isort = df4.sort_index(axis=1, ascending=False)
print(df4_isort) # 4 2 1 1 0
运行结果:
1 4 0 1 2
2 -0.416686 -0.161256 0.088802 -0.004294 1.164138
1 -0.671914 0.531256 0.303222 -0.509493 -0.342573
1 1.988321 -0.466987 2.787891 -1.105912 0.889082
4 2 1 1 0
2 -0.161256 1.164138 -0.416686 -0.004294 0.088802
1 0.531256 -0.342573 -0.671914 -0.509493 0.303222
1 -0.466987 0.889082 1.988321 -1.105912 2.787891
2. 按值排序
sort_values(by=‘column name’)
根据某个唯一的列名进行排序,如果有其他相同列名则报错。
示例代码:
# 按值排序
df4_vsort = df4.sort_values(by=0, ascending=False)
print(df4_vsort)
运行结果:
1 4 0 1 2
1 1.988321 -0.466987 2.787891 -1.105912 0.889082
1 -0.671914 0.531256 0.303222 -0.509493 -0.342573
2 -0.416686 -0.161256 0.088802 -0.004294 1.164138
3.3 处理缺失数据
示例代码:
df_data = pd.DataFrame([np.random.randn(3), [1., 2., np.nan],
[np.nan, 4., np.nan], [1., 2., 3.]])
print(df_data.head())
运行结果:
0 1 2
0 -0.281885 -0.786572 0.487126
1 1.000000 2.000000 NaN
2 NaN 4.000000 NaN
3 1.000000 2.000000 3.000000
1. 判断是否存在缺失值:isnull()
示例代码:
# isnull
print(df_data.isnull())
运行结果:
0 1 2
0 False False False
1 False False True
2 True False True
3 False False False
2. 丢弃缺失数据:dropna()
根据axis轴方向,丢弃包含NaN的行或列。 示例代码:
# dropna
print(df_data.dropna()) # 默认是按行
print(df_data.dropna(axis=1)) # axis=1是按列
运行结果:
0 1 2
0 -0.281885 -0.786572 0.487126
3 1.000000 2.000000 3.000000
1
0 -0.786572
1 2.000000
2 4.000000
3 2.000000
3. 填充缺失数据:fillna()
示例代码:
# fillna
print(df_data.fillna(-100.))
运行结果:
0 1 2
0 -0.281885 -0.786572 0.487126
1 1.000000 2.000000 -100.000000
2 -100.000000 4.000000 -100.000000
3 1.000000 2.000000 3.000000
4. 层级索引(hierarchical indexing)
下面创建一个Series, 在输入索引Index时,输入了由两个子list组成的list,第一个子list是外层索引,第二个list是内层索引。
示例代码:
import pandas as pd
import numpy as np
ser_obj = pd.Series(np.random.randn(12),index=[
['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'd'],
[0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]
])
print(ser_obj)
运行结果:
a 0 0.099174
1 -0.310414
2 -0.558047
b 0 1.742445
1 1.152924
2 -0.725332
c 0 -0.150638
1 0.251660
2 0.063387
d 0 1.080605
1 0.567547
2 -0.154148
dtype: float64
4.1 MultiIndex索引对象
-
打印这个Series的索引类型,显示是MultiIndex
-
直接将索引打印出来,可以看到有lavels,和labels两个信息。levels表示两个层级中分别有那些标签,labels是每个位置分别是什么标签。
示例代码:
print(type(ser_obj.index))
print(ser_obj.index)
运行结果:
<class 'pandas.indexes.multi.MultiIndex'>
MultiIndex(levels=[['a', 'b', 'c',宝藏级全网最全的seaborn详细教程-数据分析必备手册(2万字总结)(代码片段)
数据分析必备手册-Seaborn详细教程seaborn库安装:官方文档:关系绘图relplot1.基本使用:2.添加hue参数:3.添加col和row参数:4.指定具体的列:5.绘制折线图:分类绘图1.分类散点图:1.1.stripplot:1.2.... 查看详情
宝藏级全网最全的matplotlib详细教程-数据分析必备手册(4.5万字总结)(代码片段)
【宝藏级】全网最全的Matplotlib详细教程(4.5万字总结)1.数据分析中常用图折线图:柱状图:直方图:散点图:饼状图:箱线图:更多参考:2.Matplotlib库安装:基本使用:设置图的信息... 查看详情
宝藏级全网最全的matplotlib详细教程-数据分析必备手册(4.5万字总结)(代码片段)
【宝藏级】全网最全的Matplotlib详细教程(4.5万字总结)1.数据分析中常用图折线图:柱状图:直方图:散点图:饼状图:箱线图:更多参考:2.Matplotlib库安装:基本使用:设置图的信息... 查看详情
肝帝一周总结:全网最全最细十万字python教程,学不会找我!教到你会为止!!内容超多,建议收藏慢慢看!(代码片段)
文章目录推荐:个人推荐学习系列,推荐的一定是好的!0、源码下载地址一、内容过多,前言一定要看二、python入门三、python缩进四、Python注释1.单行注释2.多行注释五、Python变量1.变量定义理解2.变量名命名3.分... 查看详情
建议收藏万字长文,教你发布鸿蒙(harmonyos)组件到maven中央仓库,全网最全教程!(代码片段)
目录1.使用组件的3种方式(1)引用同工程中的HarmonyOS组件(以调试为目的)(2)引用本地的HarmonyOS组件(3)引用Maven中央仓库中的HarmonyOS组件2.组件可以发布到哪里(1)没有自... 查看详情
万字总结!全网最全的java并发编程知识点(代码片段)
并发及并发的线程安全处理高并发处理的思路及手段1基本概念1.1并发同时拥有两个或者多个线程,如果程序在单核处理器上运行多个线程将交替地换入或者换出内存,这些线程是同时“存在"的,每个线程都处于执行过... 查看详情
万字整理,全网最详细fate集群配置总结(代码片段)
一、准备1、硬件准备一台至少12核CPU、24G内存、1T硬盘(最好SSD)和一个不低于10MB能上互联网的网络。(最好能满足上面的条件,要不然即使安装的没有问题,也可能跑不起来)。2 软件Xshell、VMwareWor... 查看详情
史上最全wireshark使用教程,8万字整理总结,建议先收藏再耐心研读
目录第 1 章 介绍...11.1. 什么是Wireshark.11.1.1. 主要应用...11.1.2. 特性...11.1.3. 捕捉多种网络接口...21.1.4. 支持多种其它程序捕捉的文件...21.1.5. 支持多格式输出...21.1.6. 对多种协议解码提供支持...21.1.7. 开源软件...21.1.8. Wire... 查看详情
史上最全wireshark使用教程,8万字整理总结,建议先收藏再耐心研读
目录第 1 章 介绍...11.1. 什么是Wireshark.11.1.1. 主要应用...11.1.2. 特性...11.1.3. 捕捉多种网络接口...21.1.4. 支持多种其它程序捕捉的文件...21.1.5. 支持多格式输出...21.1.6. 对多种协议解码提供支持...21.1.7. 开源软件...21.1.8. Wire... 查看详情
❄️全网最详细的python入门基础教程,python最全教程(非常详细,整理而来)
📢前言前两天闲来无事唠嗑,听朋友说Python是世界上最好的语言~🤡我内心很疑惑,最好的语言不是“C酷”🙈吗(狗头保命)于是想要学一学他说的这个最好的语言😏原文是一篇大佬发的,但是很多网... 查看详情
回炉重造python之numpy详细教程(2万字总结)(代码片段)
Python之numpy详细教程前言安装:Numpy库介绍安装:教程地址:Numpy数组和Python列表性能对比:NumPy数组基本用法numpy中的数组:创建数组(np.ndarray对象):ndarray常用属性:`ndarray.dtype` 查看详情
9000字深度整理:全网最详细pandas合并数据集操作总结!(代码片段)
关于如果用pandas库来实现数据集之间合并的文章其实说少也不算少,不过我总是感觉写的算不上完善,尤其针对Python初学者来说,所以今天打算来整理与总结一下,内容较多建议收藏,喜欢点赞支持,文末... 查看详情
全网最全的博客美化系列教程07.添加一个分享的按钮吧(代码片段)
全网最全的博客美化系列教程相关文章目录【全网最全的博客美化系列教程】01.添加Github项目链接【全网最全的博客美化系列教程】02.添加QQ交谈链接【全网最全的博客美化系列教程】03.给博客添加一只萌萌哒的小仓鼠【全网最... 查看详情
全网最全的博客美化系列教程08.自定义地址栏logo(代码片段)
全网最全的博客美化系列教程相关文章目录【全网最全的博客美化系列教程】01.添加Github项目链接【全网最全的博客美化系列教程】02.添加QQ交谈链接【全网最全的博客美化系列教程】03.给博客添加一只萌萌哒的小仓鼠【全网最... 查看详情
万字长文!全网最全最细mysqlsql语句大全(建议收藏)
关注我,每天分享软件测试技术干货、面试经验,想要领取测试资料、进入软件测试学习交流群的可以直接加群644956177~~这篇文章主要向大家介绍MySQLsql语句大全,主要内容包括基础应用、实用技巧、原理机制等方面,... 查看详情
全网最全的博客美化系列教程05.公告栏个性时间显示的实现(代码片段)
全网最全的博客美化系列教程相关文章目录【全网最全的博客美化系列教程】01.添加Github项目链接【全网最全的博客美化系列教程】02.添加QQ交谈链接【全网最全的博客美化系列教程】03.给博客添加一只萌萌哒的小仓鼠【全网最... 查看详情
万字保姆级pandas核心知识操作大全
👆点击关注|设为星标|干货速递👆分享最近常用到pandas做数据处理和分析,特意总结了以下常用内容。pandas常用速查引入依赖# 导入模块import pymysqlimport pandas as pdimport numpy as npimport time# 数据库from sq... 查看详情
全网最全的博客美化系列教程06.推荐和反对炫酷样式的实现(代码片段)
全网最全的博客美化系列教程相关文章目录【全网最全的博客美化系列教程】01.添加Github项目链接【全网最全的博客美化系列教程】02.添加QQ交谈链接【全网最全的博客美化系列教程】03.给博客添加一只萌萌哒的小仓鼠【全网最... 查看详情