【问题标题】:Average one field over two columns平均一个字段超过两列
【发布时间】:2018-06-12 13:54:14
【问题描述】:

我已经四处搜索并有自己的解决方案,但我相信有更好的方法来实现结果。

我有一个包含以下列的数据框:

from_country   to_country    score

from_country 和 to_country 列具有相同的条目集,例如美国、英国、中国等。对于从到到的每种组合,都有一个特定的分数。

我需要计算每个国家/地区的平均得分,无论出现在 from_country 或 to_country 字段中。

df_from = df[["from_country", "score"]].copy()
df_from.rename(columns={"from_country":"country"}, inplace=True)
df_to = df[["to_country", "score"]].copy()
df_to.rename(columns={"to_country":"country"}, inplace=True)
df_countries = pd.concat([df_from, df_to])

然后最终计算新数据帧的平均值。

有没有更好的方法?

谢谢

【问题讨论】:

    标签: python pandas dataframe group-by average


    【解决方案1】:

    您可以先stack 列,然后一个简单的groupby 将获得所有平均值。

    df.set_index('score').stack().reset_index().groupby(0).score.mean()
    

    这是一个重命名列的示例

    import pandas as pd
    df = pd.DataFrame({'from_country': ['A', 'B', 'C', 'D', 'E', 'G'],
                       'to_country': ['G', 'C', 'Z', 'X', 'A', 'A'],
                       'score': [1, 2, 3, 4, 5, 6]})
    
    stacked = df.set_index('score').stack().to_frame('country').reset_index().drop(columns='level_1')
    #    score country
    #0       1       A
    #1       1       G
    #2       2       B
    #3       2       C
    #4       3       C
    #5       3       Z
    #...
    
    stacked.groupby('country').score.mean()
    

    输出:

    country
    A    4.0
    B    2.0
    C    2.5
    D    4.0
    E    5.0
    G    3.5
    X    4.0
    Z    3.0
    Name: score, dtype: float64
    

    【讨论】:

      【解决方案2】:

      set_index + concat 的另一种方式:

      pd.concat((
          df.set_index('from_country').score, 
          df.set_index('to_country').score
      )).groupby(level=0).mean()
      
      A    4.0
      B    2.0
      C    2.5
      D    4.0
      E    5.0
      G    3.5
      X    4.0
      Z    3.0
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-04
        相关资源
        最近更新 更多