This question already has answers here:
How to pivot a dataframe
                                
                                    (2个答案)
                                
                        
                                2年前关闭。
            
                    
我有一个看起来像的数据框

Country | IndicatorName | Value
Spain   | Indicator1    | 3
Spain   | Indicator2    | 4
Germany | Indicator16   | 24
......


我想将其转换为带有IndicatorName列,Country行和Value交集的数据框

Country | Indicator 1 | Indicator 2 | Indicator 3 | ......
Spain   |     3       |     4       |   16        | ......
Germany |     23      |     232     |   232       | ......
.......


我正在尝试通过groupby([[IndicatorName“,” Value“]),但不确定如何继续

import pandas as pd
indicators = pd.read_csv("Indicators.csv")
indicators.groupbby(["IndicatorName","Value"])
.....


是否有适当的方法来解决这个问题,还是需要通过迭代来完成?

最佳答案

我不确定初始d​​f格式,因为所需的df似乎具有不同的值。
以下内容对您有帮助吗?

df = pd.DataFrame({'Country' : ['Spain', 'Spain', 'Germany'],
                   'IndicatorName':['Indicator1', 'Indicator2', 'Indicator16'],
                  'Value':[3, 4, 24]
                  })


df.pivot(index = 'Country', columns='IndicatorName', values='Value').fillna(0)


IndicatorName   Indicator1  Indicator16     Indicator2
    Country
    Germany            0.0        24.0              0.0
    Spain              3.0         0.0              4.0

关于python - 将 Pandas 中的数据框从迭代列表转换为适当的列和行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53572127/

10-12 22:09