我有下面的数据框架:
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因此,正如您所看到的,我的代码不仅像我想要的那样匹配成对的行。例如,对于id3,它在我设置的条件下匹配三行。如何才能使它只匹配成对的行,并获得所需的输出,如下所示:
id amount
2 2 5
3 2 -5
11 4 100
12 4 -100发布于 2021-09-22 12:23:45
一种方法是检查元素的负值是否存在于其自己的组中:
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 -100https://stackoverflow.com/questions/69284006
复制相似问题