简体   繁体   English

数据透视表到数据透视表,通过交换索引和列

[英]Pivot table to Pivot table, by swapping indexes and columns

supposed my dataset假设我的数据集

Name   Month   Value
A          1     120
A          3     130
A          5     140
B          1     80
B          2     110
B          4     90
C          1     150
C          4     120
C          5     190
D          1     100
D          2     105
....

As shown in the data, there are values that do not exist for each month, so first create the first pivot table to fill in the missing values,如数据所示,每个月都有不存在的值,所以先创建第一个数据透视表来填充缺失值,

df_pivot1 = (df.pivot_table(index='Month',columns='Name', values='Value'))
df_pivot1

Name     A    B    C    D
Month
    1  120   80  150  100
    2  Nan  110  Nan  105
    3  130  Nan  Nan  Nan
    4  Nan   90  120  Nan
    5  140  Nan  190  Nan

and after filling in missing values(data imputation),并在填写缺失值(数据插补)后,

Val = Assume that imputation value
Name     A    B    C    D
Month
    1  120   80  150  100
    2  Val  110  Val  105
    3  130  Val  Val  Val
    4  Val   90  120  Val
    5  140  Val  190  Val

Now what I want is to use df_pivot1 so that the index becomes the Name and the column becomes the Month .现在我想要的是使用df_pivot1以便索引成为Name并且列成为Month

output what I want输出我想要的

Month  1   2   3   4   5
Name
   A 120 Val 130 Val 140 
   B  80 110 Val  90 Val
   C 150 Val Val 120 190
   D 100 105 Val Val Val

thank you for reading.谢谢你的阅读。

估算值后尝试

df_pivot1 = df_pivot1.T

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM