【问题标题】:pandas default aggregation function for rest of the columns [duplicate]其余列的熊猫默认聚合函数[重复]
【发布时间】:2022-10-13 16:21:28
【问题描述】:

我需要分组和聚合数据框。

有些列具有特定的聚合功能,其余的我想使用first

我只是不想硬编码其余的列名,因为它可能因大小写而异。你有什么优雅的想法如何实现吗?

import pandas as pd

df = pd.DataFrame({"col1": [1,2,3,4,5],
                   "col2": ["aa","aa","bb","bb","cc"],
                   "col3": ["b","b","b","b","b"],
                   "col4": ["c","c","c","c","c"],
                   "col5": [11,12,13,14,15]}
                  )

df.groupby(["col2"]).agg({
                          "col1": "mean",
                          "col5": "max",
                          "col3": "first",
                          "col4": "first"
                          })

输出:

      col1  col5 col3 col4
col2
aa     1.5    12    b    c
bb     3.5    14    b    c
cc     5.0    15    b    c

但我不想明确指定

                          "col3": "first",
                          "col4": "first"

简单地说,groupbyagg 中未使用的所有列都应使用默认函数进行聚合。

【问题讨论】:

  • 有关使用字典设置默认函数的方法,请参见副本。在您的情况下,您可以使用d = {c: 'first' for c in df.columns} ; d['col1'] = 'mean' ; d['col5'] = 'max' ; df.groupby(["col2"]).agg(d)

标签: python pandas aggregate


【解决方案1】:

利用:

d = {"col1": "mean", "col5": "max"}

agg = {**d, **dict.fromkeys(df.columns.difference(['col2'] + list(d.keys())), 'first')}
df = df.groupby(["col2"]).agg(agg)
print (df)
      col1  col5 col3 col4
col2                      
aa     1.5    12    b    c
bb     3.5    14    b    c
cc     5.0    15    b    c

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-16
    • 2021-11-05
    • 1970-01-01
    • 2015-08-08
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多