Python 通过旋转多列重塑数据帧
嗨,我怎么能像这样旋转桌子呢Python 通过旋转多列重塑数据帧,python,pandas,pivot-table,multi-index,Python,Pandas,Pivot Table,Multi Index,嗨,我怎么能像这样旋转桌子呢 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
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
变成另一个这样:
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
year
将成为列,每一列都应使用名称进行迭代,形成成对,用作组合主键。您可以使用melt
和pivot\u 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
另一种基于
堆栈
,取消堆栈
的解决方案:
(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
使用从宽到长的
pd.wide_to_long(df,['col'],i=['name','year'],j='cols').col.unstack(level=1).reset_index()
Out[573]:
year name cols 2018 2019
0 A 1 1 4
1 A 2 2 5
2 A 3 3 6
3 B 1 7 10
4 B 2 8 11
5 B 3 9 12
很好的解决方案@coldspeed。我只是删除了aggfunc='sum'
,这样我就可以将空值保留为NaN,以便将它们作为NULL上传到数据库中,而不是“sum”会导致错误的0(零)。