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

时间:2021-03-27 19:23:03

标签: python pandas reshape

我正在尝试重现解决方案 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', 'Region code', 'Subregion', 'Country', 'Country code',
                               'IDA Status', 'FCV Status', 'Landlocked Status', 'Pillar','Indicator',
                               'Year', 'Value', 'Status', 'Measurement', 'Updated', '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()

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

我错过了什么?谢谢!

0 个答案:

没有答案