【问题标题】:Appending a GROUP BY result into original table [duplicate]将 GROUP BY 结果附加到原始表中[重复]
【发布时间】:2019-02-09 23:32:23
【问题描述】:
 col = full.groupby('state')[['demVote']].mean()

full 是原始表的名称。我如何将这个 group by 语句的结果作为一个名为 'DEM' 的列附加到原始表中?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    我认为这会起作用,如果没有,你能提供一个具体的例子吗?

    full['DEM'] = full.groupby('state').mean()['demVote']
    

    【讨论】:

      【解决方案2】:

      使用transform:

      full['DEM'] = full.groupby('state')['demVote'].transform('mean')
      

      例如:

      >>> full
         demVote state
      0        1    ca
      1        2    ca
      2        3    ny
      3        4    ny
      
      full['DEM'] = full.groupby('state')['demVote'].transform('mean')
      
      >>> full
         demVote state  DEM
      0        1    ca  1.5
      1        2    ca  1.5
      2        3    ny  3.5
      3        4    ny  3.5
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-07
        • 2019-07-02
        • 2021-11-12
        • 1970-01-01
        • 1970-01-01
        • 2020-07-31
        • 1970-01-01
        • 2017-03-28
        相关资源
        最近更新 更多