python - 为每个 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
解决方案
一种方法是检查元素的负数是否存在于其自己的组中:
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
推荐阅读
- php - 虽然循环它只打印我 1 个值,它是最后一个
- ubuntu - 无法访问部署到 ubuntu 的 .Net Core 2.1 Web 应用程序
- node.js - 在 renderStatic 期间反应头盔混合场
- deep-learning - 除了 Keras 和 Spacy,我可以使用 Stanford Core NLP 进行深度学习吗?
- c# - 使用 Ajax 渲染局部视图的问题
- reactjs - 用打字稿反应 Redux
- android - Android Studio 应用显示问题
- idris - 让 Idris 相信递归调用的整体性
- ajax - 尝试导入 json 时如何修复 django 中的 ImportError?
- unity3d - 如何在 ARCore 生成的平面上沿相机视图方向移动对象/预制件