第二章 pandas基础
import numpy as np
import pandas as pd
import xlrd
在开始学习前,请保证pandas
的版本号不低于如下所示的版本,否则请务必升级!请确认已经安装了xlrd, xlwt, openpyxl
这三个包,其中xlrd
版本不得高于2.0.0
。
pd.__version__
'1.2.3'
xlrd.__version__
'2.0.1'
一、文件的读取和写入
1. 文件读取
pandas
可以读取的文件格式有很多,这里主要介绍读取csv, excel, txt
文件。
df_csv = pd.read_csv('../data/my_csv.csv')
df_csv
col1 | col2 | col3 | col4 | col5 | |
---|---|---|---|---|---|
0 | 2 | a | 1.4 | apple | 2020/1/1 |
1 | 3 | b | 3.4 | banana | 2020/1/2 |
2 | 6 | c | 2.5 | orange | 2020/1/5 |
3 | 5 | d | 3.2 | lemon | 2020/1/7 |
df_txt = pd.read_table('../data/my_table.txt')
df_txt
col1 | col2 | col3 | col4 | |
---|---|---|---|---|
0 | 2 | a | 1.4 | apple 2020/1/1 |
1 | 3 | b | 3.4 | banana 2020/1/2 |
2 | 6 | c | 2.5 | orange 2020/1/5 |
3 | 5 | d | 3.2 | lemon 2020/1/7 |
df_excel = pd.read_excel('../data/my_excel.xlsx')
df_excel
col1 | col2 | col3 | col4 | col5 | |
---|---|---|---|---|---|
0 | 2 | a | 1.4 | apple | 2020/1/1 |
1 | 3 | b | 3.4 | banana | 2020/1/2 |
2 | 6 | c | 2.5 | orange | 2020/1/5 |
3 | 5 | d | 3.2 | lemon | 2020/1/7 |
这里有一些常用的公共参数,header=None
表示第一行不作为列名,index_col
表示把某一列或几列作为索引,索引的内容将会在第三章进行详述,usecols
表示读取列的集合,默认读取所有的列,parse_dates
表示需要转化为时间的列,关于时间序列的有关内容将在第十章讲解,nrows
表示读取的数据行数。上面这些参数在上述的三个函数里都可以使用。
pd.read_table('../data/my_table.txt', header=None) #第一行不作为列名
0 | 1 | 2 | 3 | |
---|---|---|---|---|
0 | col1 | col2 | col3 | col4 |
1 | 2 | a | 1.4 | apple 2020/1/1 |
2 | 3 | b | 3.4 | banana 2020/1/2 |
3 | 6 | c | 2.5 | orange 2020/1/5 |
4 | 5 | d | 3.2 | lemon 2020/1/7 |
pd.read_csv('../data/my_csv.csv', index_col=['col1', 'col2']) #col1和col2列作为索引
col3 | col4 | col5 | ||
---|---|---|---|---|
col1 | col2 | |||
2 | a | 1.4 | apple | 2020/1/1 |
3 | b | 3.4 | banana | 2020/1/2 |
6 | c | 2.5 | orange | 2020/1/5 |
5 | d | 3.2 | lemon | 2020/1/7 |
pd.read_table('../data/my_table.txt', usecols=['col1', 'col2']) # 只读取col1和col2列
col1 | col2 | |
---|---|---|
0 | 2 | a |
1 | 3 | b |
2 | 6 | c |
3 | 5 | d |
data = pd.read_csv('../data/my_csv.csv', parse_dates=['col5']) # 将col5转换为时间列
data
col1 | col2 | col3 | col4 | col5 | |
---|---|---|---|---|---|
0 | 2 | a | 1.4 | apple | 2020-01-01 |
1 | 3 | b | 3.4 | banana | 2020-01-02 |
2 | 6 | c | 2.5 | orange | 2020-01-05 |
3 | 5 | d | 3.2 | lemon | 2020-01-07 |
data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 5 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 col1 4 non-null int64
1 col2 4 non-null object
2 col3 4 non-null float64
3 col4 4 non-null object
4 col5 4 non-null datetime64[ns]
dtypes: datetime64[ns](1), float64(1), int64(1), object(2)
memory usage: 288.0+ bytes
pd.read_excel('../data/my_excel.xlsx', nrows=2) # 只读取前两行
col1 | col2 | col3 | col4 | col5 | |
---|---|---|---|---|---|
0 | 2 | a | 1.4 | apple | 2020/1/1 |
1 | 3 | b | 3.4 | banana | 2020/1/2 |
在读取txt
文件时,经常遇到分隔符非空格的情况,read_table
有一个分割参数sep
,它使得用户可以自定义分割符号,进行txt
数据的读取。例如,下面的读取的表以||||
为分割:
pd.read_table('../data/my_table_special_sep.txt')
col1 |||| col2 | |
---|---|
0 | TS |||| This is an apple. |
1 | GQ |||| My name is Bob. |
2 | WT |||| Well done! |
3 | PT |||| May I help you? |
上面的结果显然不是理想的,这时可以使用sep
,同时需要指定引擎为python
:
pd.read_table('../data/my_table_special_sep.txt', sep=' \|\|\|\| ', engine='python')
col1 | col2 | |
---|---|---|
0 | TS | This is an apple. |
1 | GQ | My name is Bob. |
2 | WT | Well done! |
3 | PT | May I help you? |
【WARNING】sep
是正则参数
在使用read_table
的时候需要注意,参数sep
中使用的是正则表达式,因此需要对|
进行转义变成\|
,否则无法读取到正确的结果。有关正则表达式的基本内容可以参考第八章或者其他相关资料。
【END】
2. 数据写入
一般在数据写入中,最常用的操作是把index
设置为False
,特别当索引没有特殊意义的时候,这样的行为能把索引在保存的时候去除。
df_csv.to_csv('../data/my_csv_saved.csv', index=False)
df_excel.to_excel('../data/my_excel_saved.xlsx', index=False)
pandas
中没有定义to_table
函数,但是to_csv
可以保存为txt
文件,并且允许自定义分隔符,常用制表符\t
分割:
df_txt.to_csv('../data/my_txt_saved.txt', sep='\t', index=False)
如果想要把表格快速转换为markdown
和latex
语言,可以使用to_markdown
和to_latex
函数,此处需要安装tabulate
包。
print(df_csv.to_markdown())
| | col1 | col2 | col3 | col4 | col5 |
|---:|-------:|:-------|-------:|:-------|:---------|
| 0 | 2 | a | 1.4 | apple | 2020/1/1 |
| 1 | 3 | b | 3.4 | banana | 2020/1/2 |
| 2 | 6 | c | 2.5 | orange | 2020/1/5 |
| 3 | 5 | d | 3.2 | lemon | 2020/1/7 |
print(df_csv.to_latex())
\begin{tabular}{lrlrll}
\toprule
{} & col1 & col2 & col3 & col4 & col5 \\
\midrule
0 & 2 & a & 1.4 & apple & 2020/1/1 \\
1 & 3 & b & 3.4 & banana & 2020/1/2 \\
2 & 6 & c & 2.5 & orange & 2020/1/5 \\
3 & 5 & d & 3.2 & lemon & 2020/1/7 \\
\bottomrule
\end{tabular}
二、基本数据结构
pandas
中具有两种基本的数据存储结构,存储一维values
的Series
和存储二维values
的DataFrame
,在这两种结构上定义了很多的属性和方法。
1. Series
Series
一般由四个部分组成,分别是序列的值data
、索引index
、存储类型dtype
、序列的名字name
。其中,索引也可以指定它的名字,默认为空。
s = pd.Series(data = [100, 'a', {'dic1':5}],
index = pd.Index(['id1', 20, 'third'], name='my_idx'),
dtype = 'object',
name = 'my_name')
s
my_idx
id1 100
20 a
third {'dic1': 5}
Name: my_name, dtype: object
【NOTE】object
类型
object
代表了一种混合类型,正如上面的例子中存储了整数、字符串以及Python
的字典数据结构。此外,目前pandas
把纯字符串序列也默认认为是一种object
类型的序列,但它也可以用string
类型存储,文本序列的内容会在第八章中讨论。
【END】
对于这些属性,可以通过 . 的方式来获取:
s.values
array([100, 'a', {'dic1': 5}], dtype=object)
s.index
Index(['id1', 20, 'third'], dtype='object', name='my_idx')
s.dtype
dtype('O')
s.name
'my_name'
利用.shape
可以获取序列的长度:
s.shape
(3,)
索引是pandas
中最重要的概念之一,它将在第三章中被详细地讨论。如果想要取出单个索引对应的值,可以通过[index_item]
可以取出。
2. DataFrame
DataFrame
在Series
的基础上增加了列索引,一个数据框可以由二维的data
与行列索引来构造:
data = [[1, 'a', 1.2], [2, 'b', 2.2], [3, 'c', 3.2]]
df = pd.DataFrame(data = data,
index = ['row_%d'%i for i in range(3)],
columns=['col_0', 'col_1', 'col_2'])
df
col_0 | col_1 | col_2 | |
---|---|---|---|
row_0 | 1 | a | 1.2 |
row_1 | 2 | b | 2.2 |
row_2 | 3 | c | 3.2 |
但一般而言,更多的时候会采用从列索引名到数据的映射来构造数据框,同时再加上行索引:
df = pd.DataFrame(data = {'col_0': [1,2,3],
'col_1':list('abc'),
'col_2': [1.2, 2.2, 3.2]},
index = ['row_%d'%i for i in range(3)])
df
col_0 | col_1 | col_2 | |
---|---|---|---|
row_0 | 1 | a | 1.2 |
row_1 | 2 | b | 2.2 |
row_2 | 3 | c | 3.2 |
由于这种映射关系,在DataFrame
中可以用[col_name]
与[col_list]
来取出相应的列与由多个列组成的表,结果分别为Series
和DataFrame
:
df['col_0']
row_0 1
row_1 2
row_2 3
Name: col_0, dtype: int64
df[['col_0', 'col_1']]
col_0 | col_1 | |
---|---|---|
row_0 | 1 | a |
row_1 | 2 | b |
row_2 | 3 | c |
与Series
类似,在数据框中同样可以取出相应的属性:
df.values
array([[1, 'a', 1.2],
[2, 'b', 2.2],
[3, 'c', 3.2]], dtype=object)
df.index
Index(['row_0', 'row_1', 'row_2'], dtype='object')
df.columns
Index(['col_0', 'col_1', 'col_2'], dtype='object')
df.dtypes # 返回的是值为相应列数据类型的Series
col_0 int64
col_1 object
col_2 float64
dtype: object
df.shape
(3, 3)
通过.T
可以把DataFrame
进行转置:
df.T
row_0 | row_1 | row_2 | |
---|---|---|---|
col_0 | 1 | 2 | 3 |
col_1 | a | b | c |
col_2 | 1.2 | 2.2 | 3.2 |
三、常用基本函数
为了进行举例说明,在接下来的部分和其余章节都将会使用一份learn_pandas.csv
的虚拟数据集,它记录了四所学校学生的体测个人信息。
df = pd.read_csv('../data/learn_pandas.csv')
df.columns
Index(['School', 'Grade', 'Name', 'Gender', 'Height', 'Weight', 'Transfer',
'Test_Number', 'Test_Date', 'Time_Record'],
dtype='object')
df
School | Grade | Name | Gender | Height | Weight | Transfer | Test_Number | Test_Date | Time_Record | |
---|---|---|---|---|---|---|---|---|---|---|
0 | Shanghai Jiao Tong University | Freshman | Gaopeng Yang | Female | 158.9 | 46.0 | N | 1 | 2019/10/5 | 0:04:34 |
1 | Peking University | Freshman | Changqiang You | Male | 166.5 | 70.0 | N | 1 | 2019/9/4 | 0:04:20 |
2 | Shanghai Jiao Tong University | Senior | Mei Sun | Male | 188.9 | 89.0 | N | 2 | 2019/9/12 | 0:05:22 |
3 | Fudan University | Sophomore | Xiaojuan Sun | Female | NaN | 41.0 | N | 2 | 2020/1/3 | 0:04:08 |
4 | Fudan University | Sophomore | Gaojuan You | Male | 174.0 | 74.0 | N | 2 | 2019/11/6 | 0:05:22 |
... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
195 | Fudan University | Junior | Xiaojuan Sun | Female | 153.9 | 46.0 | N | 2 | 2019/10/17 | 0:04:31 |
196 | Tsinghua University | Senior | Li Zhao | Female | 160.9 | 50.0 | N | 3 | 2019/9/22 | 0:04:03 |
197 | Shanghai Jiao Tong University | Senior | Chengqiang Chu | Female | 153.9 | 45.0 | N | 1 | 2020/1/5 | 0:04:48 |
198 | Shanghai Jiao Tong University | Senior | Chengmei Shen | Male | 175.3 | 71.0 | N | 2 | 2020/1/7 | 0:04:58 |
199 | Tsinghua University | Sophomore | Chunpeng Lv | Male | 155.7 | 51.0 | N | 1 | 2019/11/6 | 0:05:05 |
200 rows × 10 columns
上述列名依次代表学校、年级、姓名、性别、身高、体重、是否为转系生、体测场次、测试时间、1000米成绩,本章只需使用其中的前七列。
df = df[df.columns[:7]]
df
School | Grade | Name | Gender | Height | Weight | Transfer | |
---|---|---|---|---|---|---|---|
0 | Shanghai Jiao Tong University | Freshman | Gaopeng Yang | Female | 158.9 | 46.0 | N |
1 | Peking University | Freshman | Changqiang You | Male | 166.5 | 70.0 | N |
2 | Shanghai Jiao Tong University | Senior | Mei Sun | Male | 188.9 | 89.0 | N |
3 | Fudan University | Sophomore | Xiaojuan Sun | Female | NaN | 41.0 | N |
4 | Fudan University | Sophomore | Gaojuan You | Male | 174.0 | 74.0 | N |
... | ... | ... | ... | ... | ... | ... | ... |
195 | Fudan University | Junior | Xiaojuan Sun | Female | 153.9 | 46.0 | N |
196 | Tsinghua University | Senior | Li Zhao | Female | 160.9 | 50.0 | N |
197 | Shanghai Jiao Tong University | Senior | Chengqiang Chu | Female | 153.9 | 45.0 | N |
198 | Shanghai Jiao Tong University | Senior | Chengmei Shen | Male | 175.3 | 71.0 | N |
199 | Tsinghua University | Sophomore | Chunpeng Lv | Male | 155.7 | 51.0 | N |
200 rows × 7 columns
1. 汇总函数
head, tail
函数分别表示返回表或者序列的前n
行和后n
行,其中n
默认为5:
df.head(2)
School | Grade | Name | Gender | Height | Weight | Transfer | |
---|---|---|---|---|---|---|---|
0 | Shanghai Jiao Tong University | Freshman | Gaopeng Yang | Female | 158.9 | 46.0 | N |
1 | Peking University | Freshman | Changqiang You | Male | 166.5 | 70.0 | N |
df.tail(3)
School | Grade | Name | Gender | Height | Weight | Transfer | |
---|---|---|---|---|---|---|---|
197 | Shanghai Jiao Tong University | Senior | Chengqiang Chu | Female | 153.9 | 45.0 | N |
198 | Shanghai Jiao Tong University | Senior | Chengmei Shen | Male | 175.3 | 71.0 | N |
199 | Tsinghua University | Sophomore | Chunpeng Lv | Male | 155.7 | 51.0 | N |
info, describe
分别返回表的信息概况和表中数值列对应的主要统计量 :
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 200 entries, 0 to 199
Data columns (total 7 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 School 200 non-null object
1 Grade 200 non-null object
2 Name 200 non-null object
3 Gender 200 non-null object
4 Height 183 non-null float64
5 Weight 189 non-null float64
6 Transfer 188 non-null object
dtypes: float64(2), object(5)
memory usage: 11.1+ KB
df.describe()
Height | Weight | |
---|---|---|
count | 183.000000 | 189.000000 |
mean | 163.218033 | 55.015873 |
std | 8.608879 | 12.824294 |
min | 145.400000 | 34.000000 |
25% | 157.150000 | 46.000000 |
50% | 161.900000 | 51.000000 |
75% | 167.500000 | 65.000000 |
max | 193.900000 | 89.000000 |
【NOTE】更全面的数据汇总
info, describe
只能实现较少信息的展示,如果想要对一份数据集进行全面且有效的观察,特别是在列较多的情况下,推荐使用pandas-profiling包,它将在第十一章被再次提到。
【END】
2. 特征统计函数
在Series
和DataFrame
上定义了许多统计函数,最常见的是sum, mean, median, var, std, max, min
。例如,选出身高和体重列进行演示:
df_demo = df[['Height', 'Weight']]
df_demo.mean()
Height 163.218033
Weight 55.015873
dtype: float64
df_demo.max()
Height 193.9
Weight 89.0
dtype: float64
此外,需要介绍的是quantile, count, idxmax
这三个函数,它们分别返回的是分位数、非缺失值个数、最大值对应的索引:
df_demo.quantile(0.75) # 四分之三分位数
Height 167.5
Weight 65.0
Name: 0.75, dtype: float64
df_demo.count() #计数(null不计)
Height 183
Weight 189
dtype: int64
df_demo.idxmax() # 最大值对应的索引,idxmin是对应的函数
Height 193
Weight 2
dtype: int64
上面这些所有的函数,由于操作后返回的是标量,所以又称为聚合函数,它们有一个公共参数axis
,默认为0代表逐列聚合,如果设置为1则表示逐行聚合:
df_demo.mean(axis=1).head() # 在这个数据集上体重和身高的均值并没有意义
0 102.45
1 118.25
2 138.95
3 41.00
4 124.00
dtype: float64
3. 唯一值函数
对序列使用unique
和nunique
可以分别得到其唯一值组成的列表和唯一值的个数:
df['School'].unique()
array(['Shanghai Jiao Tong University', 'Peking University',
'Fudan University', 'Tsinghua University'], dtype=object)
df['School'].nunique()
4
value_counts
可以得到唯一值和其对应出现的频数:
df['School'].value_counts()
Tsinghua University 69
Shanghai Jiao Tong University 57
Fudan University 40
Peking University 34
Name: School, dtype: int64
如果想要观察多个列组合的唯一值,可以使用drop_duplicates
。其中的关键参数是keep
,默认值first
表示每个组合保留第一次出现的所在行,last
表示保留最后一次出现的所在行,False
表示把所有重复组合所在的行剔除。
df_demo = df[['Gender','Transfer','Name']]
df_demo.drop_duplicates(['Gender', 'Transfer'])
Gender | Transfer | Name | |
---|---|---|---|
0 | Female | N | Gaopeng Yang |
1 | Male | N | Changqiang You |
12 | Female | NaN | Peng You |
21 | Male | NaN | Xiaopeng Shen |
36 | Male | Y | Xiaojuan Qin |
43 | Female | Y | Gaoli Feng |
df_demo.drop_duplicates(['Gender', 'Transfer'], keep='last')
Gender | Transfer | Name | |
---|---|---|---|
147 | Male | NaN | Juan You |
150 | Male | Y | Chengpeng You |
169 | Female | Y | Chengquan Qin |
194 | Female | NaN | Yanmei Qian |
197 | Female | N | Chengqiang Chu |
199 | Male | N | Chunpeng Lv |
df_demo.drop_duplicates(['Name', 'Gender'], keep=False).head() # 保留只出现过一次的性别和姓名组合
Gender | Transfer | Name | |
---|---|---|---|
0 | Female | N | Gaopeng Yang |
1 | Male | N | Changqiang You |
2 | Male | N | Mei Sun |
4 | Male | N | Gaojuan You |
5 | Female | N | Xiaoli Qian |
df['School'].drop_duplicates() # 在Series上也可以使用
0 Shanghai Jiao Tong University
1 Peking University
3 Fudan University
5 Tsinghua University
Name: School, dtype: object
此外,duplicated
和drop_duplicates
的功能类似,但前者返回了是否为唯一值的布尔列表,其keep
参数与后者一致。其返回的序列,把重复元素设为True
,否则为False
。 drop_duplicates
等价于把duplicated
为True
的对应行剔除。
df_demo.duplicated(['Gender', 'Transfer']).head()
0 False
1 False
2 True
3 True
4 True
dtype: bool
df['School'].duplicated().head() # 在Series上也可以使用
0 False
1 False
2 True
3 False
4 True
Name: School, dtype: bool
4. 替换函数
一般而言,替换操作是针对某一个列进行的,因此下面的例子都以Series
举例。pandas
中的替换函数可以归纳为三类:映射替换、逻辑替换、数值替换。其中映射替换包含replace
方法、第八章中的str.replace
方法以及第九章中的cat.codes
方法,此处介绍replace
的用法。
在replace
中,可以通过字典构造,或者传入两个列表来进行替换:
df['Gender'].replace({'Female':0, 'Male':1}).head()
0 0
1 1
2 1
3 0
4 1
Name: Gender, dtype: int64
df['Gender'].replace(['Female', 'Male'], [0, 1]).head()
0 0
1 1
2 1
3 0
4 1
Name: Gender, dtype: int64
另外,replace
还有一种特殊的方向替换,指定method
参数为ffill
则为用前面一个最近的未被替换的值进行替换,bfill
则使用后面最近的未被替换的值进行替换。从下面的例子可以看到,它们的结果是不同的:
s = pd.Series(['a', 1, 'b', 2, 1, 1, 'a'])
s.replace([1, 2], method='ffill')
0 a
1 a
2 b
3 b
4 b
5 b
6 a
dtype: object
s.replace([1, 2], method='bfill')
0 a
1 b
2 b
3 a
4 a
5 a
6 a
dtype: object
【WARNING】正则替换请使用str.replace
虽然对于replace
而言可以使用正则替换,但是当前版本下对于string
类型的正则替换还存在bug
,因此如有此需求,请选择str.replace
进行替换操作,具体的方式将在第八章中讲解。
【END】
逻辑替换包括了where
和mask
,这两个函数是完全对称的:where
函数在传入条件为False
的对应行进行替换,而mask
在传入条件为True
的对应行进行替换,当不指定替换值时,替换为缺失值。
s = pd.Series([-1, 1.2345, 100, -40])
s.where(s<0)
0 -1.0
1 NaN
2 NaN
3 -40.0
dtype: float64
s.where(s<0, 100)
0 -1.0
1 100.0
2 100.0
3 -40.0
dtype: float64
s.mask(s<0)
0 NaN
1 1.2345
2 100.0000
3 NaN
dtype: float64
s.mask(s<0, -50)
0 -50.0000
1 1.2345
2 100.0000
3 -50.0000
dtype: float64
需要注意的是,传入的条件只需是与被调用的Series
索引一致的布尔序列即可:
s_condition= pd.Series([True,False,False,True],index=s.index)
s.mask(s_condition, -50)
0 -50.0000
1 1.2345
2 100.0000
3 -50.0000
dtype: float64
s.where(s_condition, -50)
0 -1.0
1 -50.0
2 -50.0
3 -40.0
dtype: float64
数值替换包含了round, abs, clip
方法,它们分别表示按照给定精度四舍五入、取绝对值和截断:
s = pd.Series([-1, 1.2345, 100, -50])
s.round(2) # 四舍五入,保留两位小数
0 -1.00
1 1.23
2 100.00
3 -50.00
dtype: float64
s.abs() # 绝对值
0 1.0000
1 1.2345
2 100.0000
3 50.0000
dtype: float64
s.clip(0, 2) # 前两个数分别表示上下截断边界
0 0.0000
1 1.2345
2 2.0000
3 0.0000
dtype: float64
【练一练】
在 clip 中,超过边界的只能截断为边界值,如果要把超出边界的替换为自定义的值,应当如何做?
【END】
s.clip(0, 2).replace([0,2],[-100,100])
0 -100.0000
1 1.2345
2 100.0000
3 -100.0000
dtype: float64
5. 排序函数
排序共有两种方式,其一为值排序,其二为索引排序,对应的函数是sort_values
和sort_index
。
为了演示排序函数,下面先利用set_index
方法把年级和姓名两列作为索引,多级索引的内容和索引设置的方法将在第三章进行详细讲解。
df_demo = df[['Grade', 'Name', 'Height', 'Weight']].set_index(['Grade','Name'])
df_demo.head(3)
Height | Weight | ||
---|---|---|---|
Grade | Name | ||
Freshman | Gaopeng Yang | 158.9 | 46.0 |
Changqiang You | 166.5 | 70.0 | |
Senior | Mei Sun | 188.9 | 89.0 |
对身高进行排序,默认参数ascending=True
为升序:
df_demo.sort_values('Height').head()
Height | Weight | ||
---|---|---|---|
Grade | Name | ||
Junior | Xiaoli Chu | 145.4 | 34.0 |
Senior | Gaomei Lv | 147.3 | 34.0 |
Sophomore | Peng Han | 147.8 | 34.0 |
Senior | Changli Lv | 148.7 | 41.0 |
Sophomore | Changjuan You | 150.5 | 40.0 |
df_demo.sort_values('Height', ascending=False).head()
Height | Weight | ||
---|---|---|---|
Grade | Name | ||
Senior | Xiaoqiang Qin | 193.9 | 79.0 |
Mei Sun | 188.9 | 89.0 | |
Gaoli Zhao | 186.5 | 83.0 | |
Freshman | Qiang Han | 185.3 | 87.0 |
Senior | Qiang Zheng | 183.9 | 87.0 |
在排序中,经常遇到多列排序的问题,比如在体重相同的情况下,对身高进行排序,并且保持身高降序排列,体重升序排列:
df_demo.sort_values(['Weight','Height'],ascending=[True,False]).head()
Height | Weight | ||
---|---|---|---|
Grade | Name | ||
Sophomore | Peng Han | 147.8 | 34.0 |
Senior | Gaomei Lv | 147.3 | 34.0 |
Junior | Xiaoli Chu | 145.4 | 34.0 |
Sophomore | Qiang Zhou | 150.5 | 36.0 |
Freshman | Yanqiang Xu | 152.4 | 38.0 |
索引排序的用法和值排序完全一致,只不过元素的值在索引中,此时需要指定索引层的名字或者层号,用参数level
表示。另外,需要注意的是字符串的排列顺序由字母顺序决定。
df_demo.sort_index(level=['Grade','Name'],ascending=[True,False]).head()
Height | Weight | ||
---|---|---|---|
Grade | Name | ||
Freshman | Yanquan Wang | 163.5 | 55.0 |
Yanqiang Xu | 152.4 | 38.0 | |
Yanqiang Feng | 162.3 | 51.0 | |
Yanpeng Lv | NaN | 65.0 | |
Yanli Zhang | 165.1 | 52.0 |
6. apply方法
apply
方法常用于DataFrame
的行迭代或者列迭代,它的axis
含义与第2小节中的统计聚合函数一致,apply
的参数往往是一个以序列为输入的函数。例如对于.mean()
,使用apply
可以如下地写出:
df_demo = df[['Height', 'Weight']]
def my_mean(x):
res = x.mean()
return res
df_demo.apply(my_mean)
Height 163.218033
Weight 55.015873
dtype: float64
同样的,可以利用lambda
表达式使得书写简洁,这里的x
就指代被调用的df_demo
表中逐个输入的序列:
df_demo.apply(lambda x:x.mean())
Height 163.218033
Weight 55.015873
dtype: float64
若指定axis=1
,那么每次传入函数的就是行元素组成的Series
,其结果与之前的逐行均值结果一致。
df_demo.apply(lambda x:x.mean(), axis=1).head()
0 102.45
1 118.25
2 138.95
3 41.00
4 124.00
dtype: float64
这里再举一个例子:mad
函数返回的是一个序列中偏离该序列均值的绝对值大小的均值,例如序列1,3,7,10中,均值为5.25,每一个元素偏离的绝对值为4.25,2.25,1.75,4.75,这个偏离序列的均值为3.25。现在利用apply
计算升高和体重的mad
指标:
df_demo.apply(lambda x:(x-x.mean()).abs().mean())
Height 6.707229
Weight 10.391870
dtype: float64
这与使用内置的mad
函数计算结果一致:
df_demo.mad()
Height 6.707229
Weight 10.391870
dtype: float64
【WARNING】谨慎使用apply
得益于传入自定义函数的处理,apply
的自由度很高,但这是以性能为代价的。一般而言,使用pandas
的内置函数处理和apply
来处理同一个任务,其速度会相差较多,因此只有在确实存在自定义需求的情境下才考虑使用apply
。
【END】
%timeit -n 100 df_demo.apply(lambda x:x.mean())
465 µs ± 35.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit -n 100 df_demo.mean()
352 µs ± 17.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
四、窗口对象
pandas
中有3类窗口,分别是滑动窗口rolling
、扩张窗口expanding
以及指数加权窗口ewm
。需要说明的是,以日期偏置为窗口大小的滑动窗口将在第十章讨论,指数加权窗口见本章练习。
1. 滑窗对象
要使用滑窗函数,就必须先要对一个序列使用.rolling
得到滑窗对象,其最重要的参数为窗口大小window
。
s = pd.Series([1,2,3,4,5])
roller = s.rolling(window = 3)
roller
Rolling [window=3,center=False,axis=0]
在得到了滑窗对象后,能够使用相应的聚合函数进行计算,需要注意的是窗口包含当前行所在的元素,例如在第四个位置进行均值运算时,应当计算(2+3+4)/3,而不是(1+2+3)/3:
roller.mean()
0 NaN
1 NaN
2 2.0
3 3.0
4 4.0
dtype: float64
roller1 = s.rolling(window = 3,center = True)
roller1.mean()
0 NaN
1 2.0
2 3.0
3 4.0
4 NaN
dtype: float64
roller.sum()
0 NaN
1 NaN
2 6.0
3 9.0
4 12.0
dtype: float64
roller1.sum()
0 NaN
1 6.0
2 9.0
3 12.0
4 NaN
dtype: float64
对于滑动相关系数或滑动协方差的计算,可以如下写出:
s2 = pd.Series([1,2,6,16,30])
roller.cov(s2)
0 NaN
1 NaN
2 2.5
3 7.0
4 12.0
dtype: float64
roller.corr(s2)
0 NaN
1 NaN
2 0.944911
3 0.970725
4 0.995402
dtype: float64
此外,还支持使用apply
传入自定义函数,其传入值是对应窗口的Series
,例如上述的均值函数可以等效表示:
roller.apply(lambda x:x.mean())
0 NaN
1 NaN
2 2.0
3 3.0
4 4.0
dtype: float64
shift, diff, pct_change
是一组类滑窗函数,它们的公共参数为periods=n
,默认为1,分别表示取向前第n
个元素的值、与向前第n
个元素做差(与Numpy
中不同,后者表示n
阶差分)、与向前第n
个元素相比计算增长率。这里的n
可以为负,表示反方向的类似操作。
s = pd.Series([1,3,6,10,15])
s.shift(2)
0 NaN
1 NaN
2 1.0
3 3.0
4 6.0
dtype: float64
s.diff(3)
0 NaN
1 NaN
2 NaN
3 9.0
4 12.0
dtype: float64
s.pct_change() # 当前元素 - 前一个元素 / 前一个元素
0 NaN
1 2.000000
2 1.000000
3 0.666667
4 0.500000
dtype: float64
s.shift(-1) # 后移一个元素
0 3.0
1 6.0
2 10.0
3 15.0
4 NaN
dtype: float64
s
0 1
1 3
2 6
3 10
4 15
dtype: int64
s.diff(-1) # 当前元素 - 后一个元素
0 -2.0
1 -3.0
2 -4.0
3 -5.0
4 NaN
dtype: float64
将其视作类滑窗函数的原因是,它们的功能可以用窗口大小为n+1
的rolling
方法等价代替:
s.rolling(3).apply(lambda x:list(x)[0]) # s.shift(2)
0 NaN
1 NaN
2 1.0
3 3.0
4 6.0
dtype: float64
s.rolling(4).apply(lambda x:list(x)[-1]-list(x)[0]) # s.diff(3)
0 NaN
1 NaN
2 NaN
3 9.0
4 12.0
dtype: float64
def my_pct(x):
L = list(x)
return L[-1]/L[0]-1
s.rolling(2).apply(my_pct) # s.pct_change()
0 NaN
1 2.000000
2 1.000000
3 0.666667
4 0.500000
dtype: float64
【练一练】
rolling
对象的默认窗口方向都是向前的,某些情况下用户需要向后的窗口,例如对1,2,3设定向后窗口为2的sum
操作,结果为3,5,NaN,此时应该如何实现向后的滑窗操作?
【END】
s = pd.Series([1,2,3])
s.rolling(pd.api.indexers.FixedForwardWindowIndexer(window_size=2)).sum()
0 3.0
1 5.0
2 NaN
dtype: float64
2. 扩张窗口
扩张窗口又称累计窗口,可以理解为一个动态长度的窗口,其窗口的大小就是从序列开始处到具体操作的对应位置,其使用的聚合函数会作用于这些逐步扩张的窗口上。具体地说,设序列为a1, a2, a3, a4,则其每个位置对应的窗口即[a1]、[a1, a2]、[a1, a2, a3]、[a1, a2, a3, a4]。
s = pd.Series([1, 3, 6, 10])
s.expanding().mean()
0 1.000000
1 2.000000
2 3.333333
3 5.000000
dtype: float64
【练一练】
cummax, cumsum, cumprod
函数是典型的类扩张窗口函数,请使用expanding
对象依次实现它们。
【END】
s.expanding().max()
0 1.0
1 3.0
2 6.0
3 10.0
dtype: float64
s.expanding().sum()
0 1.0
1 4.0
2 10.0
3 20.0
dtype: float64
np.cumprod(s)
0 1
1 3
2 18
3 180
dtype: int64
s.expanding().apply(lambda x : np.prod(x))
0 1.0
1 3.0
2 18.0
3 180.0
dtype: float64
五、练习
Ex1:口袋妖怪数据集
现有一份口袋妖怪的数据集,下面进行一些背景说明:
-
#
代表全国图鉴编号,不同行存在相同数字则表示为该妖怪的不同状态 -
妖怪具有单属性和双属性两种,对于单属性的妖怪,
Type 2
为缺失值 -
Total, HP, Attack, Defense, Sp. Atk, Sp. Def, Speed
分别代表种族值、体力、物攻、防御、特攻、特防、速度,其中种族值为后6项之和
df = pd.read_csv('../data/pokemon.csv')
df.head()
# | Name | Type 1 | Type 2 | Total | HP | Attack | Defense | Sp. Atk | Sp. Def | Speed | |
---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1 | Bulbasaur | Grass | Poison | 318 | 45 | 49 | 49 | 65 | 65 | 45 |
1 | 2 | Ivysaur | Grass | Poison | 405 | 60 | 62 | 63 | 80 | 80 | 60 |
2 | 3 | Venusaur | Grass | Poison | 525 | 80 | 82 | 83 | 100 | 100 | 80 |
3 | 3 | VenusaurMega Venusaur | Grass | Poison | 625 | 80 | 100 | 123 | 122 | 120 | 80 |
4 | 4 | Charmander | Fire | NaN | 309 | 39 | 52 | 43 | 60 | 50 | 65 |
-
对
HP, Attack, Defense, Sp. Atk, Sp. Def, Speed
进行加总,验证是否为Total
值。 -
对于
#
重复的妖怪只保留第一条记录,解决以下问题:
- 求第一属性的种类数量和前三多数量对应的种类
- 求第一属性和第二属性的组合种类
- 求尚未出现过的属性组合
- 按照下述要求,构造
Series
:
- 取出物攻,超过120的替换为
high
,不足50的替换为low
,否则设为mid
- 取出第一属性,分别用
replace
和apply
替换所有字母为大写 - 求每个妖怪六项能力的离差,即所有能力中偏离中位数最大的值,添加到
df
并从大到小排序
# 1 对HP, Attack, Defense, Sp. Atk, Sp. Def, Speed进行加总,验证是否为Total值
df[["HP","Attack","Defense","Sp. Atk","Sp. Def","Speed"]].sum(1) == df["Total"]
0 True
1 True
2 True
3 True
4 True
...
795 True
796 True
797 True
798 True
799 True
Length: 800, dtype: bool
#2 对于#重复的妖怪只保留第一条记录,解决以下问题:
"""
求第一属性的种类数量和前三多数量对应的种类
求第一属性和第二属性的组合种类
求尚未出现过的属性组合
"""
df = df.drop_duplicates(["#"],keep = "first")
df["Type 1"].value_counts().head(3)
df[["Type 1","Type 2"]].value_counts()
Type 1 Type 2
Normal Flying 23
Grass Poison 14
Bug Flying 13
Poison 11
Water Ground 9
..
Rock Dark 1
Fire Rock 1
Psychic 1
Ground Steel 1
Water Steel 1
Length: 125, dtype: int64
len(df['Type 1'])
721
L_full = [i+' '+j if i!=j else i for i in df['Type 1'].unique() for j in df['Type 1'].unique()]
L_part = [df['Type 1'].iloc[i]+' '+df['Type 1'].iloc[i] for i in range(len(df['Type 1']))]
res = set(L_full).difference(set(L_part))
len(res) # 太多,不打印了
324
df["Type 1"]
0 Grass
1 Grass
2 Grass
4 Fire
5 Fire
...
793 Dark
794 Dragon
795 Rock
797 Psychic
799 Fire
Name: Type 1, Length: 721, dtype: object
"""
按照下述要求,构造Series:
取出物攻,超过120的替换为high,不足50的替换为low,否则设为mid
取出第一属性,分别用replace和apply替换所有字母为大写
求每个妖怪六项能力的离差,即所有能力中偏离中位数最大的值,添加到df并从大到小排序
"""
df["Attack"].clip(50,120).replace([50,120],["low","high"]).mask((50<=df['Attack'])&(df['Attack']<=120), 'mid')
df["Type 1"].apply(lambda str:str.upper())
df["Type 1"].replace({i:str.upper(i) for i in df['Type 1'].unique()})
med = df[["HP","Attack","Defense","Sp. Atk","Sp. Def","Speed"]].median(axis =1)
df["licha"] = df[["HP","Attack","Defense","Sp. Atk","Sp. Def","Speed"]].sub(med,axis = 0).max(axis =1)
df.sort_values(["licha"],ascending = False)
# | Name | Type 1 | Type 2 | Total | HP | Attack | Defense | Sp. Atk | Sp. Def | Speed | licha | |
---|---|---|---|---|---|---|---|---|---|---|---|---|
230 | 213 | Shuckle | Bug | Rock | 505 | 20 | 10 | 230 | 10 | 230 | 5 | 215.0 |
121 | 113 | Chansey | Normal | NaN | 450 | 250 | 5 | 5 | 35 | 105 | 50 | 207.5 |
261 | 242 | Blissey | Normal | NaN | 540 | 255 | 10 | 10 | 75 | 135 | 55 | 190.0 |
217 | 202 | Wobbuffet | Psychic | NaN | 405 | 190 | 33 | 58 | 33 | 58 | 33 | 144.5 |
223 | 208 | Steelix | Steel | Ground | 510 | 75 | 85 | 200 | 55 | 65 | 30 | 130.0 |
... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
538 | 481 | Mesprit | Psychic | NaN | 580 | 80 | 105 | 105 | 105 | 105 | 80 | 0.0 |
396 | 362 | Glalie | Ice | NaN | 480 | 80 | 80 | 80 | 80 | 80 | 80 | 0.0 |
760 | 690 | Skrelp | Poison | Water | 320 | 50 | 60 | 60 | 60 | 60 | 30 | 0.0 |
143 | 132 | Ditto | Normal | NaN | 288 | 48 | 48 | 48 | 48 | 48 | 48 | 0.0 |
395 | 361 | Snorunt | Ice | NaN | 300 | 50 | 50 | 50 | 50 | 50 | 50 | 0.0 |
721 rows × 12 columns
Ex2:指数加权窗口
- 作为扩张窗口的
ewm
窗口
在扩张窗口中,用户可以使用各类函数进行历史的累计指标统计,但这些内置的统计函数往往把窗口中的所有元素赋予了同样的权重。事实上,可以给出不同的权重来赋给窗口中的元素,指数加权窗口就是这样一种特殊的扩张窗口。
其中,最重要的参数是alpha
,它决定了默认情况下的窗口权重为
w
i
=
(
1
−
α
)
i
,
i
∈
{
0
,
1
,
.
.
.
,
t
}
w_i=(1−\alpha)^i,i\in\{0,1,...,t\}
wi=(1−α)i,i∈{0,1,...,t},其中
i
=
t
i=t
i=t表示当前元素,
i
=
0
i=0
i=0表示序列的第一个元素。
从权重公式可以看出,离开当前值越远则权重越小,若记原序列为
x
x
x,更新后的当前元素为
y
t
y_t
yt,此时通过加权公式归一化后可知:
公式
对于Series
而言,可以用ewm
对象如下计算指数平滑后的序列:
np.random.seed(0)
s = pd.Series(np.random.randint(-1,2,30).cumsum())
s
0 -1
1 -1
2 -2
3 -2
4 -2
5 -1
6 -2
7 -1
8 -2
9 -3
10 -4
11 -3
12 -3
13 -2
14 -1
15 -2
16 -2
17 -2
18 -2
19 -2
20 -3
21 -3
22 -4
23 -5
24 -5
25 -4
26 -5
27 -4
28 -5
29 -5
dtype: int32
s.ewm(alpha=0.2).mean().head()
0 -1.000000
1 -1.000000
2 -1.409836
3 -1.609756
4 -1.725845
dtype: float64
#请用expanding窗口实现
s.expanding().apply(func)
0 -1.000000
1 -1.000000
2 -1.409836
3 -1.609756
4 -1.725845
5 -1.529101
6 -1.648273
7 -1.492481
8 -1.609720
9 -1.921223
10 -2.376048
11 -2.510047
12 -2.613738
13 -2.485343
14 -2.177441
15 -2.140925
16 -2.112091
17 -2.089261
18 -2.071148
19 -2.056753
20 -2.247158
21 -2.398846
22 -2.720978
23 -3.178945
24 -3.544537
25 -3.635906
26 -3.909386
27 -3.927544
28 -4.142368
29 -4.314107
dtype: float64
请用expanding
窗口实现。
- 作为滑动窗口的
ewm
窗口
从第1问中可以看到,ewm
作为一种扩张窗口的特例,只能从序列的第一个元素开始加权。现在希望给定一个限制窗口n
,只对包含自身的最近的n
个元素作为窗口进行滑动加权平滑。请根据滑窗函数,给出新的wi
与yt
的更新公式,并通过rolling
窗口实现这一功能。
def func(x, alpha=0.2):
win = (1-alpha)**np.arange(x.shape[0])[::-1]
res = (win*x).sum()/win.sum()
return res
s.rolling(window = 3).apply(func)
0 NaN
1 NaN
2 -1.409836
3 -1.737705
4 -2.000000
5 -1.590164
6 -1.672131
7 -1.327869
8 -1.672131
9 -2.147541
10 -3.147541
11 -3.327869
12 -3.262295
13 -2.590164
14 -1.852459
15 -1.672131
16 -1.737705
17 -2.000000
18 -2.000000
19 -2.000000
20 -2.409836
21 -2.737705
22 -3.409836
23 -4.147541
24 -4.737705
25 -4.590164
26 -4.672131
27 -4.327869
28 -4.672131
29 -4.737705
dtype: float64