【问题标题】:Data wrangling with Python Pandas and pivoting使用 Python Pandas 处理数据并进行数据透视
【发布时间】:2020-10-19 20:15:13
【问题描述】:

我有一个简单的 DataFrame,其中包含不同年份、地区和国家/地区的人口数据:

df = pd.DataFrame({'country': ['one', 'one', 'one', 'two', 'two',
                           'two'],
                   'region': ['A', 'B', 'C', 'D', 'E', 'C'],
                   'population 2015': [10, 20, 30, 40, 50, 90],
                   'population 2016': [100, 200, 300, 400, 500, 900]})

我如下旋转 DataFrame,将其转换为特定结构:

df1 = df.pivot(index='region', columns='country', values=['population 2015', 'population 2016']).fillna(0)
df1

现在,我正在努力计算每个地区每年的总人口。我想以一种有效且可概括的方式做到这一点,例如不使用循环。但也许通过使用 .apply() 和 .sum() 方法,或者使用 lambda 函数。

输出应该类似于:

df = pd.DataFrame({'region': ['A', 'B', 'C', 'D', 'E'],
                   'population 2015': [10, 20, 120, 40, 50],
                   'population 2016': [100, 200, 1200, 400, 500]})

非常感谢您提前提供的帮助!

【问题讨论】:

    标签: python pandas dataframe pivot apply


    【解决方案1】:

    您可以使用levelsum

    df1 = df1.sum(level=0, axis=1).reset_index()
    print(df1)
    

    输出

      region  population 2015  population 2016
    0      A             10.0            100.0
    1      B             20.0            200.0
    2      C            120.0           1200.0
    3      D             40.0            400.0
    4      E             50.0            500.0
    

    匹配输出格式

    df1 = df1.sum(level=0, axis=1).reset_index()
    df1.iloc[:, 1:] = df1.iloc[:, 1:].astype(int)
    print(df1)
    
      region  population 2015  population 2016
    0      A               10              100
    1      B               20              200
    2      C              120             1200
    3      D               40              400
    4      E               50              500
    

    【讨论】:

    • 添加了一个答案。请让我知道这对你有没有用。如果它确实考虑接受/勾选答案。
    • 您好,谢谢您的回答。它工作得很好!计算权重:如何将旋转后的 DataFrame 除以您提供的答案,例如“2015 年人口”的两列除以您答案的“2015 年人口”列(以及 2016 年)?我认为 .DataFrame.divide() 方法会起作用。也许一切都可以一口气完成?非常感谢。
    • 嗨,很高兴它有帮助。如果您有足够的声誉,传统是接受和支持。你是对的!使用此df1 = df1.div(df1.sum(axis=1, level=0), level=0) 可以轻松计算权重。编码快乐!
    猜你喜欢
    • 2017-03-16
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2018-01-31
    • 1970-01-01
    相关资源
    最近更新 更多