微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在熊猫中仅将两列从长数据帧转换为宽格式

如何解决在熊猫中仅将两列从长数据帧转换为宽格式

我正在尝试重现解决方from this answer,但在某处犯了错误

我有一个包含多列的数据框:

'Region','Region code','Subregion','Country','Country code','IDA Status','FCV Status','Landlocked Status','Pillar','Indicator','Year','Value','Status','Measurement','Updated','Sources'

我需要将两个长列转换为宽格式:

Indicator     Status    Value

Indicator 1   Actual    20
Indicator 2   Actual    30
Indicator 3   Actual    40
Indicator 1   Forecast  30
Indicator 2   Forecast  40
Indicator 3   Forecast  50
Indicator 1   Target    60
Indicator 2   Target    60
Indicator 3   Target    60

我想把它从 2 列变成 9 列

Indicator1_Actual | Indicator1_Forecast | Indicator1_Target | Indicator2_Actual

20                  30                    60                  60

我正在根据上面的问题解决问题

foo['idx'] = foo.groupby('Region').cumcount() + 1
foo = foo.pivot_table(index = ['Region','Sources'],columns = 'idx',values = ['Indicator','Status'],aggfunc = 'first')

foo = foo.sort_index(axis = 1,level = 1)
foo.columns = [f'{x}_{y}' for x,y in foo.columns]
foo = foo.reset_index()

但我没有收到任何有意义的输出,数据帧保持不变。

我错过了什么?谢谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。