gpt4 book ai didi

Python:如果两列具有相同的值,则对第三列的值求和

转载 作者:太空宇宙 更新时间:2023-11-03 13:35:18 25 4
gpt4 key购买 nike

我有以下数据框 df

df
a b i
0 1.0 3.0 2.0
1 1.0 3.0 3.0
2 1.0 3.0 1.0
3 1.0 3.0 3.0
4 1.0 3.0 7.0
5 1.0 3.0 8.0
6 1.0 4.0 4.0
7 1.0 4.0 0.0
8 1.0 3.0 2.0
9 1.0 3.0 1.0
10 1.0 3.0 2.0

我想对同一对 ab 求和 i,所以

df2
a b i
0 1.0 3.0 31.0
1 1.0 4.0 4.0
2 1.0 3.0 0.0

df2 = df2.groupby(['a', 'b']).sum(['i']).reset_index()

最佳答案

我认为你需要在 groupby 的末尾添加 i 列,然后它用于 sum 函数:

df2 = df2.groupby(['a', 'b'])['i'].sum().reset_index()
print (df2)
a b i
0 1.0 3.0 29.0
1 1.0 4.0 4.0

或者为返回df添加参数as_index=False:

df2 = df2.groupby(['a', 'b'], as_index=False)['i'].sum()
print (df2)
a b i
0 1.0 3.0 29.0
1 1.0 4.0 4.0

如有必要,另一种解决方案是使用 Series:

df2 = df2.i.groupby([df2.a,df2.b]).sum().reset_index()
print (df2)
a b i
0 1.0 3.0 29.0
1 1.0 4.0 4.0

编辑:

如果需要在 df 中按位置区分组,请使用 groupby by Series g with aggregate :

ab = df2[['a','b']]

#compare shifted values
print (ab.ne(ab.shift()))
a b
0 True True
1 False False
2 False False
3 False False
4 False False
5 False False
6 False True
7 False False
8 False True
9 False False
10 False False
#check at least one True
print (ab.ne(ab.shift()).any(1))
0 True
1 False
2 False
3 False
4 False
5 False
6 True
7 False
8 True
9 False
10 False
dtype: bool
#use cumulative sum of boolean Series
g = ab.ne(ab.shift()).any(1).cumsum()
print (g)
0 1
1 1
2 1
3 1
4 1
5 1
6 2
7 2
8 3
9 3
10 3
dtype: int32
print (df2.groupby(g).agg(dict(a='first', b='first', i='sum')))
a b i
1 1.0 3.0 24.0
2 1.0 4.0 4.0
3 1.0 3.0 5.0

关于Python:如果两列具有相同的值,则对第三列的值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40876571/

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