gpt4 book ai didi

python - 使用重复索引 reshape Pandas Dataframe

转载 作者:太空宇宙 更新时间:2023-11-04 10:02:52 24 4
gpt4 key购买 nike

当前数据框:

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 列的每个值转换为不同的列,这些列应包含来自 Value 列的相应行的数据。
例如,在进行 reshape 之后:

CountryName Year TX.VAL.MRCH.RS.ZS TX.VAL.MRCH.R1.ZS  
Arab World 1960 1.646954e+01 2.260207e+00
Arab World 1961 1.244584e+01 1.860104e+00

最终的 Dataframe 列应该是:

[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:不允许使用负尺寸

最佳答案

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

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

enter image description here

一些解释:

这里传递的参数是按位置的,即它们是按照值、索引和列的顺序或者:

df.pivot_table(values = "Value", index = ["CountryName", "Year"], columns = "IndicatorCode").reset_index()

是填充最终数据框单元格的内容,索引 是经过去重并在结果中保留为列的列, columns 变量是在结果中转换为列标题的变量。

关于python - 使用重复索引 reshape Pandas Dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42614982/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com