【Task 2】Pandas基础

 

一、文件的读取和写入

1. 文件读取

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

其中的公共参数为:

  • 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'])  # 拿两列做索引
## 结果 
           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
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)
  • to_table(): 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 中具有两种基本的数据存储结构:

  •  Series:存储一维 values
  •  DataFrame:存储二维 values 

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

注意:

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:获取序列的长度
  • [index_item] :取出单个索引对应的值
s.shape
## 结果
(3,)


s['third']  # 取出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)],  # 列表推导式 将 i 填入 %d 中,生成索引 row_0、row_1、row_2。
                   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

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

## 列名依次代表学校、年级、姓名、性别、身高、体重、是否为转系生、体测场次、测试时间、1000米成绩。

1. 汇总函数

  • head():表示返回表或者序列的前 n 行, n 默认为5。
  • tail(): 表示返回表或者序列的后 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. 特征统计函数

最常见的统计函数:

  • sum
  • mean
  • median
  • var
  • std
  • max
  • min 
  • 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 则表示逐行聚合。

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. 替换函数

一般而言,替换操作是针对某一个列进行的。

pandas 中的替换函数可以归纳为三类:映射替换、逻辑替换、数值替换。

其中映射替换包含 replace 方法、str.replace 方法、 cat.codes 方法。

在 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

逻辑替换包括:

  • 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

数值替换包含:

  • 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,2)之间的数原数保留显示,在 <0 或者 >2 之间的数,与哪个数离的近,就使用哪个数进行替换 
## 结果 
0    0.0000
1    1.2345
2    2.0000
3    0.0000
dtype: float64

补充:

在 clip 中,超过边界的只能截断为边界值,如果要把超出边界的替换为自定义的值,可以使用 where() 和 mask(),这两个函数是完全对称的。

a = df.clip(-4,6)  #  where 和 mask ,这两个函数是完全对称的
a.where(a<0,8)     # where()函数当条件为假时,进行替换

## 结果
col_0	col_1
0	8	-2
1	-3	-4
2	8	8
3	-1	8
4	8	-4



a = df.clip(-4,6)
a.mask(a<0,-8)    # mask() 函数当条件为真时,进行替换

## 结果
col_0	col_1
0	6	-8
1	-8	-8
2	0	6
3	-8	6
4	5	-8

5. 排序函数

排序共有两种方式:

  • sort_values:值排序
  • sort_index:索引排序
df_demo = df[['Grade', 'Name', 'Height',
               'Weight']].set_index(['Grade','Name'])  # set_index 方法把年级和姓名两列作为索引

df_demo.sort_values('Height').head()  # 对身高进行排序,默认参数 ascending=True 为升序
## 结果 
                         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

对身高进行排序,默认参数 ascending=True 为升序。

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

6. apply方法

apply 方法常用于 DataFrame 的行迭代或者列迭代,apply 的参数往往是一个以序列为输入的函数。

  •  .mean()
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 表达式:使得书写简洁
df_demo.apply(lambda x:x.mean())  # x 就指代被调用的 df_demo 表中逐个输入的序列
## 结果 
Height    163.218033
Weight     55.015873
dtype: float64
  • mad():返回的是一个序列中偏离该序列均值的绝对值大小的均值
df_demo.apply(lambda x:(x-x.mean()).abs().mean())  # 用 apply 计算升高和体重的 mad 指标
## 结果 
Height     6.707229
Weight    10.391870
dtype: float64


df_demo.mad()  ## 用内置的 mad 函数计算结果一致
## 结果 
Height     6.707229
Weight    10.391870
dtype: float64

四、窗口对象

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]

首先我们设置的窗口window=3,也就是3个数取一个均值。index0, index1 为NaN,是因为它们前面都不够3个数,等到index2 的时候,它的值计算方式为(index0+index1+index2)/3,index3 的值就是(index1+index2+index3)/3,第n个元素的值将是nn-1n-2元素的平均值。

引用文章:( Pandas 窗口函数

滑动相关系数或滑动协方差的计算:

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

下面是一组类滑窗函数,它们的公共参数为 periods=n ,默认为1,

  • shift():表示取向前第 n 个元素的值
  • diff():与向前第 n 个元素做差(与 Numpy 中不同,后者表示 n 阶差分)
  • pct_change():与向前第 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

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]    1/1 = 1
1    2.000000    # [1, 3]      (1+3)/2 = 2    
2    3.333333    # [1, 3, 6]     (1+3+6)/3 = 3.3333...
3    5.000000    # [1, 3, 6, 10]   (1+3+6+10)/4 = 5
dtype: float64

五、练习

Ex1:口袋妖怪数据集

现有一份口袋妖怪的数据集,下面进行一些背景说明:

  • # 代表全国图鉴编号,不同行存在相同数字则表示为该妖怪的不同状态

  • 妖怪具有单属性和双属性两种,对于单属性的妖怪, Type 2 为缺失值

  • Total, HP, Attack, Defense, Sp. Atk, Sp. Def, Speed 分别代表种族值、体力、物攻、防御、特攻、特防、速度,其中种族值为后6项之和

    In [116]: df = pd.read_csv('data/pokemon.csv')
    
    In [117]: df.head(3)
    Out[117]: 
       #       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

     

  1. 对 HP, Attack, Defense, Sp. Atk, Sp. Def, Speed 进行加总,验证是否为 Total 值。

  2. 对于 # 重复的妖怪只保留第一条记录,解决以下问题:

        a.求第一属性的种类数量和前三多数量对应的种类

        b.求第一属性和第二属性的组合种类

        c.求尚未出现过的属性组合

     3. 按照下述要求,构造 Series :

        a.取出物攻,超过120的替换为 high ,不足50的替换为 low ,否则设为 mid

        b.取出第一属性,分别用 replace 和 apply 替换所有字母为大写

        c.求每个妖怪六项能力的离差,即所有能力中偏离中位数最大的值,添加到 df 并从大到小排序

        

# 1.
df = pd.read_csv('data/pokemon.csv')
(df[['HP', 'Attack', 'Defense', 'Sp. Atk', 'Sp. Def', 'Speed']].sum(1)!=df['Total']).mean()


# 2.
## a
dp_dup = df.drop_duplicates('#', keep='first')
dp_dup['Type 1'].nunique()
## 结果
18

dp_dup['Type 1'].value_counts().index[:3]
## 结果
Index(['Water', 'Normal', 'Grass'], dtype='object')

## b
attr_dup = dp_dup.drop_duplicates(['Type 1', 'Type 2'])
attr_dup.shape[0]
## 结果
143

## c
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 = [i+' '+j if not isinstance(j, float) else i for i, j in zip(df['Type 1'], df['Type 2'])]

res = set(L_full).difference(set(L_part))
res  # 有 170 种


# 3.
## a
df['Attack'].mask(df['Attack']>120, 'high').mask(df['Attack']<50, 'low').mask((50<=df['Attack'])&(df['Attack']<=120), 'mid').head()
## 结果 
0    low
1    mid
2    mid
3    mid
4    mid
Name: Attack, dtype: object

## b
df['Type 1'].replace({i:str.upper(i) for i in df['Type 1'
].unique()}).head()
## 结果 
0    GRASS
1    GRASS
2    GRASS
3    GRASS
4     FIRE
Name: Type 1, dtype: object

df['Type 1'].apply(lambda x:str.upper(x)).head()
## 结果 
0    GRASS
1    GRASS
2    GRASS
3    GRASS
4     FIRE
Name: Type 1, dtype: object

## c
df['Deviation'] = df[['HP', 'Attack', 'Defense', 'Sp. Atk',
'Sp. Def', 'Speed']].apply(lambda x:np.max(
(x-x.median()).abs()), 1)

df.sort_values('Deviation', ascending=False).head()
## 结果 
       #                 Name  Type 1  Type 2  Total   HP  Attack  Defense  Sp. Atk  Sp. Def  Speed  Deviation
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
333  306    AggronMega Aggron   Steel     NaN    630   70     140      230       60       80     50      155.0
224  208  SteelixMega Steelix   Steel  Ground    610   75     125      230       55       95     30      145.0

 

Ex2:指数加权窗口

  1. 作为扩张窗口的 ewm 窗口

在扩张窗口中,用户可以使用各类函数进行历史的累计指标统计,但这些内置的统计函数往往把窗口中的所有元素赋予了同样的权重。事实上,可以给出不同的权重来赋给窗口中的元素,指数加权窗口就是这样一种特殊的扩张窗口。

对于 Series 而言,可以用 ewm 对象如下计算指数平滑后的序列:

In [118]: np.random.seed(0)

In [119]: s = pd.Series(np.random.randint(-1,2,30).cumsum())

In [120]: s.head()
Out[120]: 
0   -1
1   -1
2   -2
3   -2
4   -2
dtype: int32

In [121]: s.ewm(alpha=0.2).mean().head()
Out[121]: 
0   -1.000000
1   -1.000000
2   -1.409836
3   -1.609756
4   -1.725845
dtype: float64

请用 expanding 窗口实现。

np.random.seed(0)

s = pd.Series(np.random.randint(-1,2,30).cumsum())

s.ewm(alpha=0.2).mean().head()
## 结果
0   -1.000000
1   -1.000000
2   -1.409836
3   -1.609756
4   -1.725845
dtype: float64

def ewm_func(x, alpha=0.2):
win = (1-alpha)**np.arange(x.shape[0])[::-1]
res = (win*x).sum()/win.sum()
return res

s.expanding().apply(ewm_func).head()
## 结果 
0   -1.000000
1   -1.000000
2   -1.409836
3   -1.609756
4   -1.725845
dtype: float64

 

     2.作为滑动窗口的 ewm 窗口

s.rolling(window=4).apply(ewm_func).head() # 无需对原函数改动
## 结果
0         NaN
1         NaN
2         NaN
3   -1.609756
4   -1.826558
dtype: float64

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Pandas是一个开源的Python数据分析库,提供了高效的数据结构和数据分析工具。其中的DataFrame是Pandas中最重要的数据结构之一,它是一个表格型的数据结构,含有一组有序的列。可以将DataFrame看作是由Series组成的字典\[1\]。 在使用DataFrame时,可以通过import pandas as pd导入Pandas库,并使用pd.DataFrame()函数创建DataFrame对象。可以通过指定字典的方式创建DataFrame,也可以通过读取CSV文件创建DataFrame\[1\]。 DataFrame对象有一些常用的属性。例如,可以使用index属性获取索引,使用T属性进行转置,使用columns属性获取列索引,使用values属性获取值数组,使用describe()方法获取快速统计信息\[3\]。 此外,Pandas还提供了一些绘图功能。可以使用matplotlib.pyplot库中的plot()函数绘制股票图像,通过读取CSV文件创建的DataFrame对象可以方便地进行数据可视化\[2\]。 总之,Pandas是一个功能强大的数据分析库,通过DataFrame这个数据结构,可以方便地进行数据处理、分析和可视化操作。 #### 引用[.reference_title] - *1* *2* *3* [Python pandas基础入门](https://blog.csdn.net/Dream_ya/article/details/124275302)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值