简体   繁体   English

熊猫重塑和堆叠数据帧

[英]Pandas reshaping and stacking dataframe

I have an excel sheet in this format:我有一个这种格式的excel表:

Source Hour Min1  Min2  Min3
online 0    0     0     0
online 1    1     2     0
online 2    3     4     5

How do I use pandas to transform it to this format?如何使用 pandas 将其转换为这种格式?

Hour 0                    1                    2
     Min1   Min2   Min3   Min1   Min2   Min3   Min1   Min2   Min3
     0      0      0      1      2      0      3      4      5

I've tried the following:我尝试了以下方法:

df= df.set_index(["Source", "Hour"])
stacked = df.stack()

but I got this which is almost what I need but it essentially needs to be rotated但我得到了这几乎是我需要的但它基本上需要旋转

Source  Hour
online  0     Min1     0
              Min2     0
              Min3     0
        1     Min1     1
              Min2     2
              Min3     0
        2     Min1     3
              Min2     4
              Min3     5

只需执行T ,注意我会建议将Source保留为列中的第一级

out = stacked.to_frame(0).T

I think you are looking for unstack instead:我认为您正在寻找unstack代替:

out = df.set_index(['Source','Hour']).unstack('Hour')

Or similarly, pivot :或者类似地, pivot

out = df.pivot('Source', 'Hour')

Output输出

          Min1       Min2       Min3      
Hour      0  1  2    0  1  2    0  1  2
Source                                 
online    0  1  3    0  2  4    0  0  5

To get the correct ordering as the expected output, we can do a swaplevel and sort_index :为了获得作为预期输出的正确排序,我们可以执行swaplevelsort_index

out.swaplevel(0,1, axis=1).sort_index(axis=1)

Output:输出:

Hour      0              1              2          
       Min1 Min2 Min3 Min1 Min2 Min3 Min1 Min2 Min3
Source                                             
online    0    0    0    1    2    0    3    4    5

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

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