Data Whale第20期组队学习 Pandas学习—变形

Data Whale第20期组队学习 Pandas学习—变形

  • 一、长宽表的变形
    • 1.1 pivot
    • 1.2 pivot_table
    • 1.3 melt
    • 1.4 wide_to_long
  • 二、索引的变形
    • 2.1 stack与unstack
    • 2.2 聚合与变形的关系
  • 三、其他变形函数
    • 3.1 crosstab
    • 3.2 explode
    • 3.3 get_dummies
  • 参考文献

一、长宽表的变形

长表和宽表是对于某一个特征而言的,例如一个表中把性别存储在某一个列中,那么它就是关于性别的长表;如果把性别作为列名,列中的元素是某一其他的相关特征数值,那么这个表是关于性别的宽表。

import pandas as pd
import numpy as np
df=pd.DataFrame({
     'Gender':['F','F','M','M','F','F'],
                 'Height':[163, 160, 175, 180,165,175]})
print("df=",df)
# df=   Gender  Height
# 0      F     163
# 1      F     160
# 2      M     175
# 3      M     180
# 4      F     165
# 5      F     175
df1=pd.DataFrame({
     'Height: F':[163, 160,180],
                  'Height: M':[175, 180,169]})
print("df1=",df1)
# df1=    Height: F  Height: M
# 0        163        175
# 1        160        180
# 2        180        169

从上述代码中可以看出,表df和表df1从信息上是完全等价的,都包含相同的身高统计数值,只是这些数值的呈现方式不同,而其呈现方式主要与性别一列选择的布局模式有关,即到底是以 long 的状态存储还是以 wide 的状态存储。因此, pandas 针对此类长宽表的变形操作设计了一些有关的变形函数。

1.1 pivot

pivot 是一种典型的长表变宽表的函数

df2=pd.DataFrame({
     'Class':[1,3,2,4,1,3],
                  'Name':['San Zhang','Xiao Zhang','Si Wang','Si Li','Er Wang','Wu Liu'],
                  'Subject':['Chinese','Math','Chinese','Math','Chinese','Math'],
                  'Grade':[80,75,90,85,70,95]})
print("df2=",df2)
# df2=    Class        Name  Subject  Grade
# 0      1   San Zhang  Chinese     80
# 1      3  Xiao Zhang     Math     75
# 2      2     Si Wang  Chinese     90
# 3      4       Si Li     Math     85
# 4      1     Er Wang  Chinese     70
# 5      3      Wu Liu     Math     95

相对于一个基本的长变宽的操作,最重要的是知道变形后的行索引、需要转到列索引的列,以及这些列和行索引对应的数值,它们分别对应了 pivot 方法中的 index, columns, values 参数。新生成表的列索引是 columns 对应列的 unique 值,而新表的行索引是 index 对应列的 unique 值,而 values 对应了想要展示的数值列。

print("df2.pivot(index='Name', columns='Subject', values='Grade')=",
      df2.pivot(index='Name', columns='Subject', values='Grade'))
# df2.pivot(index='Name', columns='Subject', values='Grade')= Subject     Chinese  Math
# Name                     
# Er Wang        70.0   NaN
# San Zhang      80.0   NaN
# Si Li           NaN  85.0
# Si Wang        90.0   NaN
# Wu Liu          NaN  95.0
# Xiao Zhang      NaN  75.0

pandas 从 1.1.0 开始, pivot 相关的三个参数允许被设置为列表,即意味会返回多级索引。这里构造一个相应的例子来说明如何使用:下表中六列分别为班级、姓名、测试类型(期中考试和期末考试)、科目、成绩、排名。
代码如下:

df3 = pd.DataFrame({
     'Class':[1, 1, 2, 2, 1, 1, 2, 2],'Name':['San Zhang', 'San Zhang', 'Si Li', 'Si Li','San Zhang', 'San Zhang', 'Si Li', 'Si Li'],
                    'Examination': ['Mid', 'Final', 'Mid', 'Final','Mid', 'Final', 'Mid', 'Final'],
                    'Subject':['Chinese', 'Chinese', 'Chinese', 'Chinese','Math', 'Math', 'Math', 'Math'],
                    'Grade':[80, 75, 85, 65, 90, 85, 92, 88],'rank':[10, 15, 21, 15, 20, 7, 6, 2]})
print("df3=",df3)
# df3=    Class       Name Examination  Subject  Grade  rank
# 0      1  San Zhang         Mid  Chinese     80    10
# 1      1  San Zhang       Final  Chinese     75    15
# 2      2      Si Li         Mid  Chinese     85    21
# 3      2      Si Li       Final  Chinese     65    15
# 4      1  San Zhang         Mid     Math     90    20
# 5      1  San Zhang       Final     Math     85     7
# 6      2      Si Li         Mid     Math     92     6
# 7      2      Si Li       Final     Math     88     2
"""
把测试类型和科目联合组成的四个类别
(期中语文、期末语文、期中数学、期末数学)转到列索引,并且同时统计成绩和排名
"""
pivot_multi = df3.pivot(index = ['Class', 'Name'],
                       columns = ['Subject','Examination'],values = ['Grade','rank'])
print("pivot_multi=",pivot_multi)
# pivot_multi=                   Grade                     rank                 
# Subject         Chinese       Math       Chinese       Math      
# Examination         Mid Final  Mid Final     Mid Final  Mid Final
# Class Name                                                       
# 1     San Zhang      80    75   90    85      10    15   20     7
# 2     Si Li          85    65   92    88      21    15    6     2

根据唯一性原则,新表的行索引等价于对 index 中的多列使用 drop_duplicates ,而列索引的长度为 values 中的元素个数乘以 columns 的唯一组合数量(与 index 类似)。

1.2 pivot_table

pivot 的使用依赖于唯一性条件,那如果不满足唯一性条件,那么必须通过聚合操作使得相同行列组合对应的多个值变为一个值。


"""
张三和李四都参加了两次语文考试和数学考试,按照学院规定,
最后的成绩是两次考试分数的平均值,此时就无法通过 pivot 函数来完成
"""
df4 = pd.DataFrame({
     'Name':['San Zhang', 'San Zhang','Si Li', 'Si Li','San Zhang', 'San Zhang','Si Li', 'Si Li'],
                    'Subject':['Chinese', 'Chinese', 'Math', 'Math','Chinese', 'Chinese', 'Math', 'Math'],
                    'Grade':[80, 90, 100, 90, 70, 80, 85, 95]})
print("df4=",df4)
# df4=         Name  Subject  Grade
# 0  San Zhang  Chinese     80
# 1  San Zhang  Chinese     90
# 2      Si Li     Math    100
# 3      Si Li     Math     90
# 4  San Zhang  Chinese     70
# 5  San Zhang  Chinese     80
# 6      Si Li     Math     85
# 7      Si Li     Math     95

pandas 中提供了 pivot_table 来实现,其中的 aggfunc 参数就是使用的聚合函数

print("df4.pivot_table(index = 'Name',columns = 'Subject',values='Grade',aggfunc = 'mean'",
      df4.pivot_table(index = 'Name',columns = 'Subject',values='Grade',aggfunc = 'mean'))
# df4.pivot_table(index = 'Name',columns = 'Subject',values='Grade',aggfunc = 'mean' Subject    Chinese  Math
# Name                    
# San Zhang     80.0   NaN
# Si Li          NaN  92.5

传入 aggfunc 包含了上一章中介绍的所有合法聚合字符串,还可以传入以序列为输入标量为输出的聚合函数来实现自定义操作。

print("df4.pivot_table(index = 'Name',columns = 'Subject',values = 'Grade',aggfunc = lambda x:x.mean())=",
      df4.pivot_table(index = 'Name',columns = 'Subject',values = 'Grade',aggfunc = lambda x:x.mean()))
# df4.pivot_table(index = 'Name',columns = 'Subject',values = 'Grade',aggfunc = lambda x:x.mean())= Subject    Chinese  Math
# Name                    
# San Zhang     80.0   NaN
# Si Li          NaN  92.5

此外, pivot_table 具有边际汇总的功能,可以通过设置 margins=True 来实现,其中边际的聚合方式与 aggfunc 中给出的聚合方法一致。

"""
分别统计了语文均分和数学均分、张三均分和李四均分,以及总体所有分数的均分:
"""
print("df4.pivot_table(index = 'Name',columns = 'Subject',values = 'Grade',aggfunc='mean',margins=True)=",
      df4.pivot_table(index = 'Name',columns = 'Subject',values = 'Grade',aggfunc='mean',margins=True))
# df4.pivot_table(index = 'Name',columns = 'Subject',values = 'Grade',aggfunc='mean',margins=True)= Subject    Chinese  Math    All
# Name
# San Zhang     80.0   NaN  80.00
# Si Li          NaN  92.5  92.50
# All           80.0  92.5  86.25

1.3 melt

长宽表只是数据呈现方式的差异,但其包含的信息量是等价的,前面提到了利用 pivot 把长表转为宽表,melt
函数就可以通过相应的逆操作把宽表转为长表。

df5=pd.DataFrame({
     'Class':[1,2,3],'Name':['San Zhang', 'Si Li','Wu Wang'],'Chinese':[80, 90,85],'Math':[80, 75,95]})
print("df5=",df5)
# df5=    Class       Name  Chinese  Math
# 0      1  San Zhang       80    80
# 1      2      Si Li       90    75
# 2      3    Wu Wang       85    95
df5_m=df5.melt(id_vars = ['Class', 'Name'],value_vars = ['Chinese', 'Math'],
               var_name = 'Subject',value_name = 'Grade')
print("df5_m=",df5_m)
# df5_m=    Class       Name  Subject  Grade
# 0      1  San Zhang  Chinese     80
# 1      2      Si Li  Chinese     90
# 2      3    Wu Wang  Chinese     85
# 3      1  San Zhang     Math     80
# 4      2      Si Li     Math     75
# 5      3    Wu Wang     Math     95
df5_um=df5_m.pivot(index = ['Class', 'Name'], columns='Subject',values='Grade')
print("df5_um=",df5_um)
# df5_um= Subject          Chinese  Math
# Class Name
# 1     San Zhang       80    80
# 2     Si Li           90    75
# 3     Wu Wang         85    95
df5_um=df5_um.reset_index().rename_axis(columns={
     'Subject':''})
print("df5_um.equals(df5)=",df5_um.equals(df5))
# df5_um.equals(df5)= True

1.4 wide_to_long

melt 方法中,在列索引中被压缩的一组值对应的列元素只能代表同一层次的含义,即 values_name 。现在如果列中包含了交叉类别,比如期中期末的类别和语文数学的类别,那么想要把 values_name 对应的 Grade 扩充为两列分别对应语文分数和数学分数,只把期中期末的信息压缩,这种需求下就要使用 wide_to_long 函数来完成。

df6=pd.DataFrame({
     'Class':[1,2,1],'Name':['San Zhang', 'Si Li','Liu Liu'],'Chinese_Mid':[80, 75,85],
                  'Math_Mid':[90, 85,85],'Chinese_Final':[80, 75,81], 'Math_Final':[90, 85,92]})
print("df6=",df6)
# df6=    Class       Name  Chinese_Mid  Math_Mid  Chinese_Final  Math_Final
# 0      1  San Zhang           80        90             80          90
# 1      2      Si Li           75        85             75          85
# 2      1    Liu Liu           85        85             81          92
print("pd.wide_to_long(df6,stubnames=['Chinese', 'Math'],i = ['Class', 'Name'],j='Examination',sep='_',suffix='.+')=",
      pd.wide_to_long(df6,stubnames=['Chinese', 'Math'],i = ['Class', 'Name'],j='Examination',sep='_',suffix='.+'))
# pd.wide_to_long(df6,stubnames=['Chinese', 'Math'],i = ['Class', 'Name'],j='Examination',sep='_',suffix='.+')=                              Chinese  Math
# Class Name      Examination               
# 1     San Zhang Mid               80    90
#                 Final             80    90
# 2     Si Li     Mid               75    85
#                 Final             75    85
# 1     Liu Liu   Mid               85    85
#                 Final             81    92

res = pivot_multi.copy()
res.columns = res.columns.map(lambda x:'_'.join(x))
res = res.reset_index()
res = pd.wide_to_long(res, stubnames=['Grade', 'rank'],
                      i = ['Class', 'Name'],j = 'Subject_Examination',sep = '_',suffix = '.+')
res = res.reset_index()
res[['Subject', 'Examination']] = res['Subject_Examination'].str.split('_', expand=True)
res = res[['Class', 'Name', 'Examination','Subject', 'Grade', 'rank']].sort_values('Subject')
res = res.reset_index(drop=True)
print("res=",res)
# res=    Class       Name Examination  Subject  Grade  rank
# 0      1  San Zhang         Mid  Chinese     80    10
# 1      1  San Zhang       Final  Chinese     75    15
# 2      2      Si Li         Mid  Chinese     85    21
# 3      2      Si Li       Final  Chinese     65    15
# 4      1  San Zhang         Mid     Math     90    20
# 5      1  San Zhang       Final     Math     85     7
# 6      2      Si Li         Mid     Math     92     6
# 7      2      Si Li       Final     Math     88     2

二、索引的变形

2.1 stack与unstack

利用 swaplevel 或者 reorder_levels 进行索引内部的层交换,行列索引之间 的交换导致了 DataFrame 维度上的变化,即属于变形操作。在第一节中提到的4种变形函数与其不同之处在于,它们都属于某一列或几列元素和列索引 之间的转换,而不是索引之间的转换。unstack 函数的作用是把行索引转为列索引。

df7=pd.DataFrame(np.ones((6,3)),index = pd.Index([('A', 'cat', 'pig'),('A', 'dog', 'small'),('C', 'cat', 'pig'),('C', 'dog', 'small'),
                                                  ('B', 'cat', 'pig'),('B', 'dog', 'small')]),columns=['col_1', 'col_2', 'col_3'])
print("df7=",df7)
# df7=              col_1  col_2  col_3
# A cat pig      1.0    1.0    1.0
#   dog small    1.0    1.0    1.0
# C cat pig      1.0    1.0    1.0
#   dog small    1.0    1.0    1.0
# B cat pig      1.0    1.0    1.0
#   dog small    1.0    1.0    1.0
print("df7.unstack()=",df7.unstack())
# df7.unstack()=       col_1       col_2       col_3
#         pig small   pig small   pig small
# A cat   1.0   NaN   1.0   NaN   1.0   NaN
#   dog   NaN   1.0   NaN   1.0   NaN   1.0
# B cat   1.0   NaN   1.0   NaN   1.0   NaN
#   dog   NaN   1.0   NaN   1.0   NaN   1.0
# C cat   1.0   NaN   1.0   NaN   1.0   NaN
#   dog   NaN   1.0   NaN   1.0   NaN   1.0
# unstack 的主要参数是移动的层号,默认转化最内层,移动到列索引的最内层,同时支持同时转化多个层
print("df7.unstack(1)=",df7.unstack(1))
# df7.unstack(1)=         col_1      col_2      col_3
#           cat  dog   cat  dog   cat  dog
# A pig     1.0  NaN   1.0  NaN   1.0  NaN
#   small   NaN  1.0   NaN  1.0   NaN  1.0
# B pig     1.0  NaN   1.0  NaN   1.0  NaN
#   small   NaN  1.0   NaN  1.0   NaN  1.0
# C pig     1.0  NaN   1.0  NaN   1.0  NaN
#   small   NaN  1.0   NaN  1.0   NaN  1.0
print("df7.unstack([0,2])",df7.unstack([0,2]))
# df7.unstack([0,2])     col_1                              ... col_3                            
#         A          C          B        ...     A          C          B      
#       pig small  pig small  pig small  ...   pig small  pig small  pig small
# cat   1.0   NaN  1.0   NaN  1.0   NaN  ...   1.0   NaN  1.0   NaN  1.0   NaN
# dog   NaN   1.0  NaN   1.0  NaN   1.0  ...   NaN   1.0  NaN   1.0  NaN   1.0
# 
# [2 rows x 18 columns]
df8=pd.DataFrame(np.ones((6,3)),index = pd.Index([('A', 'cat', 'big'),('A', 'dog', 'small'),('B', 'cat', 'big'),
                                                  ('B', 'dog', 'small'),('D', 'cat', 'big'),('D', 'dog', 'small')]),
                 columns=['index_1', 'index_2', 'index_3']).T
print("df8=",df8)
# df8=            A          B          D
#          cat   dog  cat   dog  cat   dog
#          big small  big small  big small
# index_1  1.0   1.0  1.0   1.0  1.0   1.0
# index_2  1.0   1.0  1.0   1.0  1.0   1.0
# index_3  1.0   1.0  1.0   1.0  1.0   1.0
print("df8.stack()=",df8.stack())
# df8.stack()=                  A         B         D
#                cat  dog  cat  dog  cat  dog
# index_1 big    1.0  NaN  1.0  NaN  1.0  NaN
#         small  NaN  1.0  NaN  1.0  NaN  1.0
# index_2 big    1.0  NaN  1.0  NaN  1.0  NaN
#         small  NaN  1.0  NaN  1.0  NaN  1.0
# index_3 big    1.0  NaN  1.0  NaN  1.0  NaN
#         small  NaN  1.0  NaN  1.0  NaN  1.0
print("df8.stack([1, 2])=",df8.stack([1, 2]))
# df8.stack([1, 2])=                      A    B    D
# index_1 cat big    1.0  1.0  1.0
#         dog small  1.0  1.0  1.0
# index_2 cat big    1.0  1.0  1.0
#         dog small  1.0  1.0  1.0
# index_3 cat big    1.0  1.0  1.0
#         dog small  1.0  1.0  1.0

2.2 聚合与变形的关系

在以上的所有函数中,除了带有聚合效果的 pivot_table 以外,所有的函数在变形前后并不会带来 values 个数的改变,只是这些值在呈现的形式上发生了变化。在分组聚合操作中,由于生成了新的行列索引,因此必然也属于某种特殊的变形操作,但是聚合之后把原来的多个值变为了一个值,因此 values 的个数产生了变化,即分组聚合与变形函数的最大区别。

三、其他变形函数

3.1 crosstab

crosstab 并不是一个值得推荐使用的函数,因为它能实现的所有功能 pivot_table 都能完成,并且速度更快。在默认状态下, crosstab 可以统计元素组合出现的频数,即 count 操作。

# 统计 learn_pandas 数据集中学校和转系情况对应的频数
df9 = pd.read_csv('data/learn_pandas.csv')
print("pd.crosstab(index = df9.School, columns = df9.Transfer)=",
      pd.crosstab(index = df9.School, columns = df9.Transfer))
# pd.crosstab(index = df9.School, columns = df9.Transfer)= Transfer                        N  Y
# School
# Fudan University               38  1
# Peking University              28  2
# Shanghai Jiao Tong University  53  0
# Tsinghua University            62  4
# 或者使用 crosstab
print("pd.crosstab(index = df9.School, columns = df9.Transfer,values = [0]*df9.shape[0], aggfunc = 'count'=",
      pd.crosstab(index = df9.School, columns = df9.Transfer,values = [0]*df9.shape[0], aggfunc = 'count'))
# pd.crosstab(index = df9.School, columns = df9.Transfer,values = [0]*df9.shape[0], aggfunc = 'count'= Transfer                          N    Y
# School
# Fudan University               38.0  1.0
# Peking University              28.0  2.0
# Shanghai Jiao Tong University  53.0  NaN
# Tsinghua University            62.0  4.0
## 利用 pivot_table 进行等价操作,由于这里统计的是组合的频数,
# 因此 values 参数无论传入哪一个列都不会影响最后的结果
print("df9.pivot_table(index = 'School',columns = 'Transfer',values = 'Name',aggfunc = 'count')=",
      df9.pivot_table(index = 'School',columns = 'Transfer',values = 'Name',aggfunc = 'count'))
# df9.pivot_table(index = 'School',columns = 'Transfer',values = 'Name',aggfunc = 'count')= Transfer                          N    Y
# School
# Fudan University               38.0  1.0
# Peking University              28.0  2.0
# Shanghai Jiao Tong University  53.0  NaN
# Tsinghua University            62.0  4.0
# 除了默认状态下的 count 统计,所有的聚合字符串和返回标量的自定义函数都是可用的,例如统计对应组合的身高均值
print("pd.crosstab(index = df9.School, columns = df9.Transfer,values = df9.Height, aggfunc = 'mean')=",
      pd.crosstab(index = df9.School, columns = df9.Transfer,values = df9.Height, aggfunc = 'mean'))
# pd.crosstab(index = df9.School, columns = df9.Transfer,values = df9.Height, aggfunc = 'mean')= Transfer                                N       Y
# School                                           
# Fudan University               162.043750  177.20
# Peking University              163.429630  162.40
# Shanghai Jiao Tong University  163.953846     NaN
# Tsinghua University            163.253571  164.55

3.2 explode

explode 参数能够对某一列的元素进行纵向的展开,被展开的单元格必须存储 list, tuple, Series, np.ndarray 中的一种类型。

df10 = pd.DataFrame({
     'Q': [[1, 2],'my_str',{
     1, 2},pd.Series([3, 4])], 'R': 1})
print("df10.explode('Q')=",df10.explode('Q'))
# df10.explode('Q')=         Q  R
# 0       1  1
# 0       2  1
# 1  my_str  1
# 2  {1, 2}  1
# 3       3  1
# 3       4  1

3.3 get_dummies

get_dummies 是用于特征构建的重要函数之一,其作用是把类别特征转为指示变量。例如,对年级一列转为指示变量,属于某一个年级的对应列标记为1,否则为0,代码如下

print("pd.get_dummies(df9.Grade).head()=",pd.get_dummies(df9.Grade).head())
# pd.get_dummies(df9.Grade).head()=    Freshman  Junior  Senior  Sophomore
# 0         1       0       0          0
# 1         1       0       0          0
# 2         0       0       1          0
# 3         0       0       0          1
# 4         0       0       0          1

参考文献

1、https://datawhalechina.github.io/joyful-pandas/build/html/%E7%9B%AE%E5%BD%95/ch5.html

你可能感兴趣的:(python基础,python)