目录
1.字符串与文本数据
2. 索引和选择数据
2.1 .loc()按标签进行选择
2.2 .iloc()按位置进行选择
2.3 使用属性获取数据
3. 统计函数
3.1 百分比变化.pct_change()
3.2 协方差.cov()
3.3 相关性.corr()
3.4 数据排名.rank()
4. 窗口函数
1.字符串与文本数据Series 支持字符串处理方法,可以非常方便地操作数组里的每个元素。这些方法会自动排除缺失值与空值,这也许是其最重要的特性。这些方法通过 Series 的 str
属性访问,一般情况下,这些操作的名称与内置的字符串方法一致,例如.lower();.upper();.len()等基础方法。
示例:
import pandas as pd
import numpy as np
s = pd.Series([' Tom ',' xiaoming ',' john '])
s
#删除空格
s.str.strip()
#字符串分割
s.str.split('o')
#字符串拼接
s.str.cat(sep="")
#辨别分类
s.str.get_dummies()
#字符串包含的内容
s.str.contains('m')
#字符串替换
s.str.replace('o',"dd")
#计数
s.str.count('i')
#对一系列字符串判断是否是数字
s = pd.Series([' Tom ','778899',' xiaoming ',' john '])
s.str.isnumeric()
输出结果:
# 原始Series
0 Tom
1 xiaoming
2 john
dtype: object
# 删除空格
0 Tom
1 xiaoming
2 john
dtype: object
# 字符串以o进行分割
0 [ T, m ]
1 [ xia, ming ]
2 [ j, hn ]
dtype: object
# 字符串拼接
' Tom xiaoming john '
# 辨别分类
Tom john xiaoming
0 1 0 0
1 0 0 1
2 0 1 0
# 字符串包含的内容
0 True
1 True
2 False
dtype: bool
# 字符串替换
0 Tddm
1 xiaddming
2 jddhn
dtype: object
# 计数(字符串中i的数量)
0 0
1 2
2 0
dtype: int64
# 对一系列字符串判断是否是数字
0 False
1 True
2 False
3 False
dtype: bool
2. 索引和选择数据
在pandas中,除了使用index下标或column列名索引外,还可以使用.loc();.iloc()进行数据索引。
2.1 .loc()按标签进行选择pandas 提供了一套方法来实现纯粹的基于标签的索引。这是一个严格的基于包含的协议。要求的每个标签都必须在索引中,否则KeyError
将被提出。切片时,如果索引中存在,则包括起始边界和停止边界。整数是有效的标签,但它们指的是标签而不是位置。
该.loc
属性是主要的访问方法。以下是有效输入:
-
单个标签,例如
5
或'a'
(请注意,它5
被解释为索引的标签。此用法不是沿索引的整数位置。)。 -
标签列表或数组。
['a', 'b', 'c']
-
带有标签的切片对象
'a':'f'
(请注意,与通常的 Python 切片相反,开始和停止都包含在索引中!请参阅带标签的切片。 -
一个布尔数组。
-
A
callable
,请参阅按 Callable 选择。
示例:随机生成一个八行撕裂的数据进行操作
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(8,4),index=['a','b','c','d','e','f','g','h'],columns=["A","B","C","D"])
df
# 输出结果
A B C D
a 0.529671 -0.076485 0.379469 1.494926
b -0.082312 -0.328869 0.175183 -0.798430
c 0.681922 0.741320 -0.910726 -2.176608
d 1.500632 -1.165229 0.316722 0.402977
e -2.044217 0.930242 0.433050 0.542472
f 1.332038 0.476599 1.661994 2.102483
g 0.488362 -1.667154 -0.651079 -0.049332
h -0.676308 0.904894 1.592176 0.409881
1. 选择AB列的所有内容(使用切片)
#选择A.B列所有的内容,基于标签
df.loc[:,['A','B']]
#输出结果
A B
a 0.529671 -0.076485
b -0.082312 -0.328869
c 0.681922 0.741320
d 1.500632 -1.165229
e -2.044217 0.930242
f 1.332038 0.476599
g 0.488362 -1.667154
h -0.676308 0.904894
2. 选择a-e行,b以后的列(切片)
#选择a-e行,b以后的列
df.loc['a':'e','B':]
# 输出结果:
B C D
a -0.076485 0.379469 1.494926
b -0.328869 0.175183 -0.798430
c 0.741320 -0.910726 -2.176608
d -1.165229 0.316722 0.402977
e 0.930242 0.433050 0.542472
3. 取出a标签中大于1的数据
# 取出a标签里大于一的数据
df.loc['a']>1
# 输出结果
A False
B False
C False
D True
Name: a, dtype: bool
4. 取出a大于1的那一列内容
# 取出a大于1的那一列内容
df.loc[:,df.loc['a']>1]
#输出结果:
D
a 1.494926
b -0.798430
c -2.176608
d 0.402977
e 0.542472
f 2.102483
g -0.049332
h 0.409881
2.2 .iloc()按位置进行选择
pandas 提供了一套方法来获得纯粹的基于整数的索引。语义紧跟 Python 和 NumPy 切片。这些是0-based
索引。切片时,包括起始边界,排除上限。尝试使用非整数,即使是有效标签也会引发IndexError
.
该.iloc
属性是主要的访问方法。以下是有效输入:
-
一个整数,例如
5
。 -
整数列表或数组。
[4, 3, 0]
-
带有 ints 的切片对象
1:7
。 -
一个布尔数组。
-
A
callable
,请参阅按 Callable 选择。
示例:继上述案例的dataframe
A B C D
a 0.529671 -0.076485 0.379469 1.494926
b -0.082312 -0.328869 0.175183 -0.798430
c 0.681922 0.741320 -0.910726 -2.176608
d 1.500632 -1.165229 0.316722 0.402977
e -2.044217 0.930242 0.433050 0.542472
f 1.332038 0.476599 1.661994 2.102483
g 0.488362 -1.667154 -0.651079 -0.049332
h -0.676308 0.904894 1.592176 0.409881
1. 基于(行)位置的索引
# 基于(行)位置的索引
df.iloc[0]
#输出结果:
A 0.529671
B -0.076485
C 0.379469
D 1.494926
Name: a, dtype: float64
df.iloc[1]
#输出结果:
A -0.082312
B -0.328869
C 0.175183
D -0.798430
Name: b, dtype: float64
2. 取出第三行第二列以后的内容
df.iloc[3:,1:]
#输出结果:
B C D
d -1.165229 0.316722 0.402977
e 0.930242 0.433050 0.542472
f 0.476599 1.661994 2.102483
g -1.667154 -0.651079 -0.049332
h 0.904894 1.592176 0.409881
2.3 使用属性获取数据
对于上述数据,在pandas中,也可以采用属性获取方式取出数据。
示例:取出A列和D列的数据
#属性获取,取出A列内容
df.A
#输出结果:
a 1.310455
b -1.015628
c 1.281924
d 0.496812
e -1.733183
f 0.140338
g -0.179063
h -0.642013
Name: A, dtype: float64
df.D
#输出结果:
a -0.298131
b -1.141310
c -0.302760
d 1.188531
e -1.608952
f 0.437460
g -0.696010
h -0.525048
Name: D, dtype: float64
3. 统计函数
pandas中提供多种统计函数供用户使用,如百分比变化.pct_change();协方差.cov();相关性.corr();数据排名.rank()方法
3.1 百分比变化.pct_change()Series
并DataFrame
有一种方法.pct_change()来计算给定周期数内的百分比变化(在计算百分比变化之前fill_method
使用填充 NA/null 值)。
基本语法:
Series.pct_change()
or
DataFrame.pct_change(periods=行数)
示例:
import pandas as pd
import numpy as np
#创建基础Series
s = pd.Series([877,865,874,890,912])
s
# 输出结果:
0 877
1 865
2 874
3 890
4 912
dtype: int64
#创建基础dataframe
df = pd.DataFrame(np.random.randn(5, 4))
df
#输出结果
0 1 2 3
0 0.655875 -2.195588 -0.785019 1.122582
1 0.852057 -2.276063 1.528201 -0.167119
2 -1.057979 -0.396548 -0.915528 0.026226
3 -0.490155 1.803235 0.005851 -1.252117
4 0.946558 -2.680471 -0.055739 -0.624553
获取变化的百分比:
# 变化的百分比程度(波动变化)
s.pct_change()
#输出结果:
0 NaN
1 -0.013683
2 0.010405
3 0.018307
4 0.024719
dtype: float64
# 变化的百分比程度
df.pct_change(periods=1)
# 输出结果:
0 1 2 3
0 NaN NaN NaN NaN
1 0.299115 0.036653 -2.946706 -1.148870
2 -2.241677 -0.825775 -1.599088 -1.156933
3 -0.536707 -5.547331 -1.006391 -48.742482
4 -2.931143 -2.486479 -10.526903 -0.501202
3.2 协方差.cov()
Series.cov()可用于计算系列之间的协方差(不包括缺失值)。
DataFrame.cov()计算DataFrame 中系列之间的成对协方差,也排除 NA/null 值。
示例:
#计算两个Series之间的协方差
s1 = pd.Series(np.random.randn(10))
s2 = pd.Series(np.random.randn(10))
#两个数据的协方差
s1.cov(s2)
#输出结果:
-0.0751790891671201
# 计算dataframe中数据的协方差
frame = pd.DataFrame(np.random.randn(1000, 5), columns=["a", "b", "c", "d", "e"])
frame.cov()
#输出结果:
a b c d e
a 1.000882 -0.003177 -0.002698 -0.006889 0.031912
b -0.003177 1.024721 0.000191 0.009212 0.000857
c -0.002698 0.000191 0.950735 -0.031743 -0.005087
d -0.006889 0.009212 -0.031743 1.002983 -0.047952
e 0.031912 0.000857 -0.005087 -0.047952 1.042487
DataFrame.cov
还支持一个可选min_periods
关键字,该关键字指定每个列对所需的最小观察次数,以便获得有效结果。例如
frame.cov(min_periods=12)
观察dataframe中最少12列数据,若不够12列则返回NaN。
3.3 相关性.corr()可以使用该.coor()方法计算相关性。使用该method
参数,提供了几种计算相关性的方法:
方法名称
描述
pearson (default)
标准相关系数
kendall
Kendall Tau 相关系数
spearman
Spearman等级相关系数
示例:
1. 两个series之间的相关性
s1 = pd.Series(np.random.randn(10))
s2 = s1*2
#相关性(s1与s2)
s1.corr(s2)
#输出结果:
0.9999999999999999
2. 三组数据之间的相关性(dataframe)
s1 = pd.Series(np.random.randn(10))
s2 = s1*2
s3 = pd.Series(np.random.randn(10))
df = pd.DataFrame({
's1':s1,
's2':s2,
's3':s3
})
df
# 输出dataframe
s1 s2 s3
0 -1.149359 -2.298718 0.742016
1 0.476084 0.952168 -0.375759
2 -0.998627 -1.997255 0.721653
3 1.047331 2.094663 -0.078039
4 0.444710 0.889420 -0.525895
5 -0.411778 -0.823557 -0.402789
6 -0.935911 -1.871822 -0.597614
7 -0.652570 -1.305140 0.636498
8 1.055361 2.110722 -0.763907
9 -1.222631 -2.445262 -0.153914
# 三者相关性
df.corr()
#输出结果:
s1 s2 s3
s1 1.000000 1.000000 -0.548589
s2 1.000000 1.000000 -0.548589
s3 -0.548589 -0.548589 1.000000
3.4 数据排名.rank()
.rank()方法生成一个数据排名,其中关系被分配了组的排名平均值,例如:
s = pd.Series([877,865,874,890,912])
s
#输出结果:
0 877
1 865
2 874
3 890
4 912
dtype: int64
s.rank()
#输出结果:
0 3.0
1 1.0
2 2.0
3 4.0
4 5.0
dtype: float64
在dataframe中,rank()可以对行 ( axis=0
) 或列 ( axis=1
) 进行排名。NaN
值被排除在排名之外。
rank
可选地采用ascending
默认为 true 的参数;如果为 false,则对数据进行反向排名,较大的值分配较小的排名。
rank
支持不同的平局方法,由method
参数指定:
-
average
: 并列组的平均排名 -
min
: 组中排名最低的 -
max
: 组内最高排名 -
first
:按照它们在数组中出现的顺序分配的排名
pandas 包含一组紧凑的 API,用于执行窗口操作 - 一种在值的滑动分区上执行聚合的操作。API 的功能与 API 类似groupby
,Series并DataFrame使用必要的参数调用窗口化方法,然后调用聚合函数。
pandas 支持 4 种类型的窗口操作:
-
滚动窗口:值上的通用固定或可变滑动窗口。
-
加权窗口:库提供的加权非矩形窗口
scipy.signal
。 -
扩展窗口:累积值的窗口。
-
指数加权窗口:值的累积和指数加权窗口。
概念
方法
返回的对象
支持基于时间的窗口
支持链式groupby
支持表格法
支持在线操作
卷帘窗
rolling
Rolling
是的
是的
是>1.3
不
加权窗口
rolling
Window
不
不
不
不
扩大窗口
expanding
Expanding
不
是的
是>1.3
不
指数加权窗口
ewm
ExponentialMovingWindow
不
是>1.2
不
是(从 1.3 版开始)
示例:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10,4))
df
#输出结果:
0 1 2 3
0 2.599818 0.451315 -0.428038 0.035233
1 0.395523 -0.098377 0.059649 -0.489922
2 0.550164 -0.469461 1.193710 0.567562
3 1.483434 -0.793989 -0.738174 0.515078
4 0.395409 0.425578 -0.439963 -0.207277
5 -0.035479 -1.438315 -0.863333 -0.129948
6 -0.336889 -0.094188 -1.452638 0.083352
7 -0.626117 0.120990 -0.566740 0.665003
8 -1.437816 -0.112235 -0.232150 -0.099910
9 -0.582537 0.388641 1.008226 0.321893
1. .rolling() 卷帘窗
# 滚动窗口求每三行之间的平均值
df.rolling(window=3).mean()
#输出结果:
0 1 2 3
0 NaN NaN NaN NaN
1 NaN NaN NaN NaN
2 1.181835 -0.038841 0.275107 0.037625
3 0.809707 -0.453942 0.171729 0.197573
4 0.809669 -0.279291 0.005191 0.291788
5 0.614455 -0.602242 -0.680490 0.059284
6 0.007681 -0.368975 -0.918644 -0.084624
7 -0.332828 -0.470504 -0.960904 0.206135
8 -0.800274 -0.028478 -0.750509 0.216148
9 -0.882157 0.132465 0.069779 0.295662
2. .expanding扩大窗口
#expanding
df.expanding(min_periods=3).mean()
#输出结果:
0 1 2 3
0 NaN NaN NaN NaN
1 NaN NaN NaN NaN
2 1.181835 -0.038841 0.275107 0.037625
3 1.257235 -0.227628 0.021787 0.156988
4 1.084869 -0.096987 -0.070563 0.084135
5 0.898145 -0.320542 -0.202691 0.048455
6 0.721711 -0.288205 -0.381255 0.053440
7 0.553233 -0.237056 -0.404441 0.129885
8 0.332005 -0.223187 -0.385297 0.104352
9 0.240551 -0.162004 -0.245945 0.126106