【问题标题】:Transform dataframe in pandas from an iterative list to proper columns and rows [duplicate]将熊猫中的数据框从迭代列表转换为正确的列和行[重复]
【发布时间】:2019-05-03 11:17:36
【问题描述】:

我有一个看起来像

的数据框
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"])
.....

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

【问题讨论】:

    标签: python pandas dataframe machine-learning


    【解决方案1】:

    我不确定初始 df 格式,因为所需的 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
    

    【讨论】:

    • 有帮助的没问题 :)
    • @arkaitz Jimenez 我还不能对你的帖子发表评论。这对我的支点很有帮助stackoverflow.com/questions/47152691/how-to-pivot-a-dataframe
    • 我收到“ValueError:索引包含重复条目,无法重塑”
    • 您好,请参阅上面的链接问题 1 答案 - 这是因为 pandas 试图重新索引具有重复条目的列或索引对象。可以使用多种方法来执行数据透视。其中一些不太适合当要求它在其中旋转的键存在重复时。您可能需要 pivot_table() 和某种形式的聚合函数
    • 是的,我想这正是我所需要的
    猜你喜欢
    • 2021-07-26
    • 2019-05-25
    • 2019-10-12
    • 1970-01-01
    • 2020-07-30
    • 2016-09-25
    • 1970-01-01
    • 2017-06-22
    • 2019-12-16
    相关资源
    最近更新 更多