熊猫将 muliindex 更改为索引和多列

时间:2021-07-01 20:05:47

标签: python pandas

我有一个这样的 df

| Feature | Channel | Value |
|---------|---------|-------|
| a       | 0       | 1.3   |
|         | 1       | 1.3   |
|         | 2       | 1.3   |
| b       | 0       | 1.2   |
|         | 1       | 1.2   |
|         | 2       | 1.2   |

其中 FeatureChannel 是多索引

如何将其转换为以下内容:

| channel | a   | b   |
|---------|-----|-----|
| 0       | 1.3 | 1.2 |
| 1       | 1.3 | 1.2 |
| 2       | 1.3 | 1.2 |

channel 现在是索引,a 和 b 是单独的列?

2 个答案:

答案 0 :(得分:2)

使用unstack

new_df = df.unstack(level=0)

new_df

        Value     
Feature     a    b
Channel           
0         1.3  1.2
1         1.3  1.2
2         1.3  1.2

使用 droplevel + rename_axis

new_df = df.unstack(0).droplevel(0, 1).rename_axis(columns=None)

new_df

           a    b
Channel          
0        1.3  1.2
1        1.3  1.2
2        1.3  1.2

答案 1 :(得分:0)

Pivot 可能更容易(先删除索引)-

df.reset_index(inplace=True)
df.pivot(index='Channel',columns='Feature',values='Value')