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

3

我有以下数据框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()
2个回答

6

我认为你需要在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

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

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中的位置区分组,请使用Series g通过aggregategroupby功能:

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

1
你想比较以查看之前的 a, b 组合是否已更改,并进行 cumsum 以建立分组数组。
ab = df[['a', 'b']].apply(tuple, 1)

df.groupby(ab.ne(ab.shift()).cumsum()) \
  .agg(dict(a='last', b='last', i='sum')) \
  .reindex_axis(df.columns.tolist(), 1)

enter image description here


将其分解开来。
  • ab = df[['a', 'b']].apply(tuple, 1)
    • 生成一个元组序列,以便查看组合是否发生了变化
  • ab.ne(ab.shift())
    • 检查元组是否与前一个元组不同
  • ab.ne(ab.shift()).cumsum()
    • 如果不同,则将True值添加到累计和中。这将为每个相同的ab对的连续集创建一个方便的分组
  • .agg(dict(a='last', b='last', i='sum'))
    • 只是指定在每个组中对每个列要执行什么操作。获取ab的最后一个值,这很好,因为我知道它在整个组中都是相同的。对列进行求和
  • .reindex_axis(df.columns.tolist(), 1)
    • 按照原来的顺序获取我的列顺序

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接