首页 > 解决方案 > 为每个 id 匹配正负数对

问题描述

我有下面的数据框:

import pandas as pd
d = {'id': [1,1,2,2,3,3,3,4,4],
    'amount':[2,3,5,-5,2,3,-5,3,4]}

d = pd.DataFrame(d)
d
   id   amount
0   1   2
1   1   3
2   2   5
3   2   -5
4   2   4
5   2   6
6   3   2
7   3   3
8   3   -5
9   4   3
10  4   4
11  4   100
12  4   -100

所以我想要做的是将正值与每个 id 的负值匹配,我这样做:

d[d.groupby(['id'])['amount'].transform('sum').eq(0)

这给了我这个输出:


   id   amount
2   2   5
3   2   -5
4   3   2
5   3   3
6   3   -5

所以你可以看到我的代码不仅匹配我想要的行对。例如,对于 id 3,它在我设置的条件下匹配三行。我怎样才能让它只匹配成对的行并获得所需的输出,如下所示:

   id   amount
2   2   5
3   2  -5
11  4   100
12  4  -100

标签: pythonpython-3.xpandasdataframedictionary

解决方案


一种方法是检查元素的负数是否存在于其自己的组中:

def refunded(data):
    return data[data["amount"].isin(-data["amount"])]

    new_df = df.groupby("id").apply(refunded).reset_index(0, drop=True)
print(new_df)

输出:

    id  amount
2    2       5
3    2      -5
11   4     100
12   4    -100

推荐阅读