使用重复索引重塑Pandas数据帧

2024-09-30 02:29:47 发布

您现在位置:Python中文网/ 问答频道 /正文

当前数据帧:

CountryName      IndicatorCode    Year         Value  
Arab World     TX.VAL.MRCH.RS.ZS  1960  1.646954e+01  
Arab World     TX.VAL.MRCH.R1.ZS  1960  2.260207e+00
Arab World     TX.VAL.MRCH.RS.ZS  1961  1.244584e+01
Arab World     TX.VAL.MRCH.R1.ZS  1961  1.860104e+00  
Zimbabwe       DT.DIS.OFFT.CD     2015  8.377700e+07
Zimbabwe       DT.INT.OFFT.CD     2015  2.321300e+07
Zimbabwe       DT.AMT.PROP.CD     2015  6.250000e+05

我想将IndicatorCode列的每个值转换为不同的列,这些列应包含值列的相应行中的数据。
例如,在进行“整形”后:

^{pr2}$

最终数据帧列应为:

[CountryName, Year, TX.VAL.MRCH.RS.ZS, TX.VAL.MRCH.R1.ZS, DT.DIS.OFFT.CD,DT.INT.OFFT.CD, DT.AMT.PROP.CD]  

我试过使用pivot,但没有成功。我不能把国家名称作为索引,因为它不是唯一的。在

temp = indicators_df.pivot(columns='IndicatorCode',  values='Value')

得到ValueError: negative dimensions are not allowed


Tags: 数据worlddtcdvalrstxr1
2条回答

您可以使用pivot_table,它接受多个列作为索引

df.pivot_table("Value", ["CountryName", "Year"], "IndicatorCode").reset_index()

enter image description here

一些解释:

这里传递的参数是按位置排列的,即它们的顺序是values, index, and columns或:

^{pr2}$

填充最终数据帧的单元格,索引是经过重复数据消除并在结果中保留为列的列,变量是在结果中以列标题为轴的变量。在

{{cd2}

s = df.set_index(['CountryName', 'Year', 'IndicatorCode']).Value
s.unstack().reset_index().rename_axis([None], 1)

enter image description here

相关问题 更多 >

    热门问题