Eve*_*eis 4 python pivot-table multi-index pandas
嗨我怎么能像这样转动一个表
import pandas as pd
d = {'name' : ['A','A','B','B'],'year': ['2018','2019','2018','2019'],'col1':[1,4,7,10],'col2':[2,5,8,11],'col3':[3,6,9,12]}
pd.DataFrame(data=d)
name year col1 col2 col3
A 2018 1 2 3
A 2019 4 5 6
B 2018 7 8 9
B 2019 10 11 12
Run Code Online (Sandbox Code Playgroud)
进入另一个像这样:
name cols 2018 2019
A col1 1 4
A col2 2 5
A col3 3 6
B col1 7 10
B col2 8 11
B col3 9 12
Run Code Online (Sandbox Code Playgroud)
year 将成为列,每列应使用名称进行迭代,以形成将用作组合主键的对.
你可以使用melt和pivot_table:
(df.melt(['name','year'], var_name='cols')
.pivot_table(index=['name', 'cols'],
columns='year',
values='value',
aggfunc='sum')
.reset_index()
.rename_axis(None, 1))
name cols 2018 2019
0 A col1 1 4
1 A col2 2 5
2 A col3 3 6
3 B col1 7 10
4 B col2 8 11
5 B col3 9 12
Run Code Online (Sandbox Code Playgroud)
一种替代stack,unstack基于溶液:
(df.set_index(['name','year'])
.stack()
.unstack(1)
.rename_axis(['name', 'cols'], 0)
.rename_axis(None, 1)
.reset_index())
name cols 2018 2019
0 A col1 1 4
1 A col2 2 5
2 A col3 3 6
3 B col1 7 10
4 B col2 8 11
5 B col3 9 12
Run Code Online (Sandbox Code Playgroud)