我有一个这样的 df
| Feature | Channel | Value |
|---------|---------|-------|
| a | 0 | 1.3 |
| | 1 | 1.3 |
| | 2 | 1.3 |
| b | 0 | 1.2 |
| | 1 | 1.2 |
| | 2 | 1.2 |
其中 Feature
和 Channel
是多索引
如何将其转换为以下内容:
| channel | a | b |
|---------|-----|-----|
| 0 | 1.3 | 1.2 |
| 1 | 1.3 | 1.2 |
| 2 | 1.3 | 1.2 |
channel 现在是索引,a 和 b 是单独的列?
答案 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')