需要重塑熊猫数据框

时间:2018-08-17 07:54:39

标签: python pandas transpose

我的输入数据框如下:

Variable | fiscal_week_id | units 
xxxxxxxxxxx | 201801 | xx_unit_201801 
xxxxxxxxxxx | 201802 | xx_unit_201802 
xxxxxxxxxxx | 201803 | xx_unit_201803 
yyyyyyyyyyy | 201801 | yy_unit_201801 
yyyyyyyyyyy | 201802 | yy_unit_201802 
yyyyyyyyyyy | 201803 | yy_unit_201803

需要这样的输出:

Variable | 201801 | 201802 | 201803 
xxxxxxxxxxx | xx_unit_201801 | xx_unit_201802 | xx_unit_201803 
yyyyyyyyyyy | yy_unit_201801 | yy_unit_201802 | yy_unit_201803

请提供任何帮助,是熊猫的新手,只需要熊猫解决方案即可。我尝试了set_index,但似乎没有解决问题。

1 个答案:

答案 0 :(得分:0)

您可以按照@jezrael的建议使用pd.pivot

res = df.pivot(index='Variable', columns='fiscal_week_id', values='units')

print(res)

fiscal_week_id          201801          201802          201803
Variable                                                      
xxxxxxxxxxx     xx_unit_201801  xx_unit_201802  xx_unit_201803
yyyyyyyyyyy     yy_unit_201801  yy_unit_201802  yy_unit_201803

上次尝试:

您可以使用pd.pivot_table。当您没有“真实”聚合功能时,可以使用'first'提取唯一的项目:

res = df.pivot_table(index='Variable', columns='fiscal_week_id',
                     values='units', aggfunc='first')