通过将行转换为列来重塑(分组或旋转)熊猫数据框

时间:2019-07-26 23:35:00

标签: pandas pivot-table pandas-groupby

我想根据这种形状重塑数据框

Country     subject    2017 2018    Frq  2017 Score     2018 Score
Argentina   subject 1   12   22     100  50.77214238    51.54316539
Argentina   subject 2   68   13     150  66.92805676    67.60645268

datafram pic 1

达到此形状

         subject  1                     subject  2                          subject  3…
Country 2017    2018    Frq 2017 Score  2018 Score  2017    2018    Frq 2017 Score  2018 Score  
Argentina   12  22  100 50.77214238 51.54316539 12  22  100 50.77214238 51.54316539 
Australia   68  13  150 66.92805676 67.60645268 68  13  150 66.92805676 67.60645268 

datafram pic 2

因此,每个国家/地区都有一行。然后将列主题的值转换为列

我尝试了以下操作,但没有产生所需的结果

pd.pivot_table(GCI, index='Country', columns=['subject'],
               values=['2017', '2018'], aggfunc='sum', fill_value=0) 

也尝试过:

pivoted_GCI = GCI[['Country']]  #pd.DataFrame()

for key,group_df in GCI.groupby('subject'):
    print("the group for '{}' has {} rows".format(key,len(group_df))) 
    group_df.name = key
    group_df = group_df.drop(['subject'], axis=1)
    display(group_df)
    pivoted_GCI = pd.merge(pivoted_GCI, group_df, on='Country', how='left')

谢谢

1 个答案:

答案 0 :(得分:0)

您可以进行unstack

s=df.set_index(['Country','subject']).stack().unstack([1,2]).reset_index()