【发布时间】:2022-01-17 15:07:58
【问题描述】:
数据框
TYPE WEEK VALUE1 VALUE2
0 Type1 1 1 1
1 Type2 2 2 2
2 Type3 3 3 3
3 Type4 4 4 4
import pandas as pd
import numpy as np
df = {'TYPE' : pd.Series(['Type1','Type2','Type3','Type4']),
'WEEK' : pd.Series([1, 2, 3, 4]),
'VALUE1' : pd.Series([1, 2, 3, 4]),
'VALUE2' : pd.Series([1, 2, 3, 4])
}
df = pd.DataFrame(df)
df = pd.pivot_table(df,index="TYPE",columns="WEEK", values=['VALUE1','VALUE2']).reset_index()
df2 = df.swaplevel(0,1,axis=1).reset_index()
输出
WEEK index 1 2 3 4 1 2 3 4
TYPE VALUE1 VALUE1 VALUE1 VALUE1 VALUE2 VALUE2 VALUE2 VALUE2
0 0 Type1 1.0 NaN NaN NaN 1.0 NaN NaN NaN
1 1 Type2 NaN 2.0 NaN NaN NaN 2.0 NaN NaN
2 2 Type3 NaN NaN 3.0 NaN NaN NaN 3.0 NaN
3 3 Type4 NaN NaN NaN 4.0 NaN NaN NaN 4.0
预期的结构输出
WEEK TYPE | VALUE11 VALUE21 | VALUE12 VALUE22 | VALUE13 VALUE23 | VALUE14 VALUE24
0 Type1 | | | |
1 Type2 | | | |
2 Type3 | | | |
3 Type4 | | | |
思考的方法:
- 重新排序结构。 (我已经尝试过
swaplevel(),但无法达到预期的输出) - 加入列名,例如。 “Value11”乘“Value1”+“1” 我浏览了互联网上的几个示例,但无法提出任何建议。
【问题讨论】:
-
是值列一个星期值和类型的串联
标签: python pandas pivot-table multi-index