首页 > 解决方案 > 计数到第一列并总结到其余列 pandas groupby

问题描述

我有一个df290 列的 pandas DataFrame。

有没有办法根据.groupby以下规则进行操作:

  1. 第二列的求和运算。
  2. 计数操作到第 3 列。
  3. 对所有其他列的平均操作

我知道我可以这样使用:

df.groupby("column1") \
    .agg({"column2":"sum", 
          "column3":"count",
          "column4":"mean",
          ...
          "column290":"mean"})

但是使用这种方式完全没有效率,因为我必须键入所有其他列。

有没有办法设置这个操作?就像我没有将任何设置为 agg 时设置默认功能一样?

标签: pythonpandasdataframegroup-by

解决方案


让我们使用字典:

import pandas as pd
import numpy as np

df=pd.DataFrame(np.arange(100).reshape(10,-1), columns=[*'ABCDEFGHIJ'])

# Defined the first three columns  
aggdict={'A':'sum',
         'B':'sum',
         'C':'count'}

# Use for loop to added to dictoary the rest of the columns. Creating a 
# default aggregation method
for i in df.columns[3:]:
    aggdict[i]='mean'

# Use agg with dictionary
df.groupby(df.index%2).agg(aggdict)

推荐阅读