[英]How to Unpivot a Pandas PivotTable?
I have the following pandas pivot table, and would like to shift only the 'Date' Column Header to a row.我有以下 pandas pivot 表,并且只想将“日期”列 Header 移动到一行。
Date JAN2022 FEB2022
ID Income Expenses Income Expenses
0 A 100 -23 10 -53
1 B 90 -20 280 -70
Desired outcome:期望的结果:
Date ID Income Expenses
0 JAN2022 A 100 -23
1 JAN2022 B 90 -20
2 FEB2022 A 10 -53
3 FEB2022 B 280 -70
-- Edited -- -- 已编辑 --
Output of df.to_dict() df.to_dict() 的 Output
{('FEB2022', 'Expenses'): {0: -53, 1: -70},
('FEB2022', 'Income'): {0: 10, 1: 280},
('ID', ''): {0: 'A', 1: 'B'},
('JAN2022', 'Expenses'): {0: -23, 1: -20},
('JAN2022', 'Income'): {0: 100, 1: 90}}
Creation of sample dataframe创建样品 dataframe
data={'Date':['JAN2022','JAN2022','FEB2022','FEB2022'],'ID':['A','B','A','B'],'Income':[100,90,10,280],'Expenses':[-23,-20,-53,-70]}
df = pd.DataFrame(data)
df = pd.pivot_table(df, index='ID', values=['Income','Expenses'], columns='Date', aggfunc='sum').swaplevel(0, 1, 1).sort_index(1).reset_index()
I'm assuming you have MultiIndex dataframe where the first column has column index ("", "ID")
- the first level of this column is empty string:我假设您有 MultiIndex dataframe ,其中第一列具有列索引
("", "ID")
-该列的第一级是空字符串:
df = df.set_index(("", "ID")).stack(level=0)
df.index.names = ["ID", "Date"]
print(df.reset_index())
Prints:印刷:
ID Date Expenses Income
0 A FEB2022 -53 10
1 A JAN2022 -23 100
2 B FEB2022 -70 280
3 B JAN2022 -20 90
EDIT: With the new data just swap the "ID", "":编辑:使用新数据只需交换“ID”,“”:
df = df.set_index(("ID", "")).stack(level=0)
df.index.names = ["ID", "Date"]
print(df.reset_index())
Prints:印刷:
ID Date Expenses Income
0 A FEB2022 -53 10
1 A JAN2022 -23 100
2 B FEB2022 -70 280
3 B JAN2022 -20 90
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.