Pandas学习(3)——Pandas基础

本文基于Datawhale提供的Pandas学习资料。
均为本人理解,如有不足或错误地方欢迎补充批评指正,如有侵权,联系速删。
开始学习前,请确认已经安装了 xlrd, xlwt, openpyxl 这三个包。其中,当pandas版本为1.2.x时,xlrd版本不得高于 2.0.0 。若pandas版本在1.3.x或以上时,xlrd正常安装即可。

一.文件的读取和写入

import numpy as np
import pandas as pd

1. 文件读取

pandas 可以读取的文件格式有很多,这里主要介绍读取 csv, excel, txt 文件。

df_csv = pd.read_csv('data/my_csv.csv')
#读取csv文件
df_txt = pd.read_table('data/my_table.txt')
#读取txt文件
df_excel = pd.read_excel('data/my_excel.xlsx')
#读取excel文件

这里有一些常用的公共参数, 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                               
# 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
# 0     2    a
# 1     3    b
# 2     6    c
# 3     5    d

pd.read_csv('data/my_csv.csv', parse_dates=['col5'])

#    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

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?

注意: sep是正则函数
在使用 read_table 的时候需要注意,参数 sep 中使用的是正则表达式,因此需要对 | 进行转义变成 | ,否则无法读取到正确的结果。

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 包。

二、基本数据结构

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')
# my_idx
# id1              100
# 20                 a
# third    {'dic1': 5}
# Name: my_name, dtype: object

object 类型
object 代表了一种混合类型,正如上面的例子中存储了整数、字符串以及 Python 的字典数据结构。此外,目前 pandas 把纯字符串序列也默认认为是一种 object 类型的序列,但它也可以用 string 类型存储。
对于这些属性,可以通过 . 的方式来获取:

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] 可以取出。

s['third']
#{'dic1': 5}

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'])

#        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)])

#        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
#Out[38]: 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 = df[df.columns[:7]]

上述列名依次代表学校、年级、姓名、性别、身高、体重、是否为转系生、体测场次、测试时间、1000米成绩。本章只需使用其中的前七列。

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

更全面的数据汇总

info, describe 只能实现较少信息的展示,如果想要对一份数据集进行全面且有效的观察,特别是在列较多的情况下,推荐使用 pandas-profiling 包,它将在第十一章被再次提到。

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()

#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
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

正则替换请使用 str.replace

虽然对于 replace 而言可以使用正则替换,但是当前版本下对于 string 类型的正则替换还存在 bug ,因此如有此需求,请选择 str.replace 进行替换操作,具体的方式将在第八章中讲解。
逻辑替换包括了 where 和 mask ,这两个函数是完全对称的: where 函数在传入条件为 False 的对应行进行替换,而 mask 在传入条件为 True 的对应行进行替换,当不指定替换值时,替换为缺失值。

s = pd.Series([-1, 1.2345, 100, -50])

s.where(s<0)
 
#0    -1.0
#1     NaN
#2     NaN
#3   -50.0
#dtype: float64

s.where(s<0, 100)

#0     -1.0
#1    100.0
#2    100.0
#3    -50.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

数值替换包含了 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
5. 排序函数

排序共有两种方式,其一为值排序,其二为索引排序,对应的函数是 sort_values 和 sort_index 。

为了演示排序函数,下面先利用 set_index 方法把年级和姓名两列作为索引,多级索引的内容和索引设置的方法将在第三章进行详细讲解。

df_demo = df[['Grade', 'Name', 'Height',
              'Weight']].set_index(['Grade','Name']

对身高进行排序,默认参数 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

谨慎使用 apply
得益于传入自定义函数的处理, apply 的自由度很高,但这是以性能为代价的。一般而言,使用 pandas 的内置函数处理和 apply 来处理同一个任务,其速度会相差较多,因此只有在确实存在自定义需求的情境下才考虑使用 apply 。

四、窗口对象

pandas 中有3类窗口,分别是滑动窗口 rolling 、扩张窗口 expanding 以及指数加权窗口 ewm 。

1. 滑窗对象

要使用滑窗函数,就必须先要对一个序列使用 .rolling 得到滑窗对象,其最重要的参数为窗口大小 window 。

s = pd.Series([1,2,3,4,5])

roller = s.rolling(window = 3)

# 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

roller.sum()

#0     NaN
#1     NaN
#2     6.0
#3     9.0
#4    12.0
#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.diff(-2)

#0   -5.0
#1   -7.0
#2   -9.0
#3    NaN
#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
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
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值