【问题标题】:How to pivot dataframe and transpose 1 row如何旋转数据框并转置 1 行
【发布时间】:2022-11-03 04:39:32
【问题描述】:

我想旋转这个数据框并将列转换为二级多索引或列。

原始数据框:

    Type        VC  C   B   Security
0   Standard    2   2   2       A
1   Standard    16  13  0       B
2   Standard    52  35  2       C
3   RI          10  10  0       A
4   RI          10  15  31      B
5   RI          10  15  31      C

所需的数据框:

    Type            A   B  C  
0   Standard VC     2   16 52
1   Standard C      2   13 35
2   Standard B      2   0  2
3   RI       VC     10  10 10
11  RI       C      10  15 15
12  RI       B      0   31 31

【问题讨论】:

标签: python pandas


【解决方案1】:

您可以尝试如下:

  • 使用df.pivot,然后使用df.T 转置。
  • 接下来,链接df.sort_index 以重新排列条目,并应用df.swaplevel 更改MultiIndex 的顺序。
  • 最后,考虑将Security 去掉为columns.name,并为未命名变量添加index.name,例如Subtype 在这里。
res = (df.pivot(index='Security', columns='Type').T
       .sort_index(level=[1,0], ascending=[False, False])
       .swaplevel(0))

res.columns.name = None
res.index.names = ['Type','Subtype']
print(res)

                   A   B   C
Type     Subtype            
Standard VC        2  16  52
         C         2  13  35
         B         2   0   2
RI       VC       10  10  10
         C        10  15  15
         B         0  31  31

【讨论】:

    猜你喜欢
    • 2019-11-14
    相关资源
    最近更新 更多