gpt4 book ai didi

Pandas Dataframe 聚合不同的列组

转载 作者:行者123 更新时间:2023-12-02 08:14:19 25 4
gpt4 key购买 nike

我有一个数据框

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

最佳答案

使用聚合

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

关于Pandas Dataframe 聚合不同的列组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43378273/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com