Pandas 数据帧聚合不同的列组

Pandas 数据帧聚合不同的列组,pandas,dataframe,group-by,aggregate,Pandas,Dataframe,Group By,Aggregate,我有一个数据帧 df = pd.DataFrame( [np.random.randint(1,10,8), np.random.randint(1,10,8), np.random.randint(1,10,8), np.random.randint(1,10,8)]).T # left col is the index >> a b c d group 0 5 6 3 2 g1 1 5 6 6 6 g1 2 3 9 5 3 g1

我有一个数据帧

df = pd.DataFrame(
[np.random.randint(1,10,8),
np.random.randint(1,10,8),
np.random.randint(1,10,8),
np.random.randint(1,10,8)]).T

# left col is the index
>> a  b  c  d group
0  5  6  3  2    g1
1  5  6  6  6    g1
2  3  9  5  3    g1
3  5  6  8  2    g1
4  2  2  9  6    g1
5  9  5  4  8    g2
6  1  3  5  2    g2
7  3  8  8  6    g2
我想按“分组”列分组,然后执行一些不同的操作:

•对于“a”列,我希望获得最小值和最大值

•对于其余部分,我想对其进行汇总

min_max_col = ['a']
sum_cols = ['b','c','d']
有没有一个简单的方法可以做到这一点? 结果应该如下所示:

>>   min  max  sum_b  sum_c  sum_d
g1    2    5     29     48     19
g2    1    9     16     48     16
使用agg

df = df.groupby('group').agg({'a':[ np.min,  np.max], 'b': np.sum, 'c': np.sum, 'd': np.sum})
df.columns = ['min', 'max', 'sum_b', 'sum_c', 'sum_d']
df = df.reset_index()


    group   min max sum_b   sum_c   sum_d
0   g1      2   5   29      31      19
1   g2      1   9   16      17      16

这是不同的,因为我们正在利用内部引用的
sum
min
max
函数。我认为,我们应该尽可能地利用这些资源

f = dict(
    a=['min', 'max'],
    b='sum',
    c='sum',
    d='sum'
)

df.groupby('group').agg(f)

        a       b   c   d
      min max sum sum sum
group                    
g1      2   5  29  31  19
g2      1   9  16  17  16

明白了,这就是答案it@RSHAP这将取决于实际用例(如何确定列等),但您可以执行类似于
dict.fromkeys(list('bcd'),'sum')
的操作。您可以像PiRsquared那样单独指定所有操作,然后传递该函数。当有很多列时,它会提高可读性,但不会减少工作量。是的。当我问哈哈时,我意识到了这一点