python - 删除在 1 列中总和为零但在熊猫中重复的行
问题描述
我有以下结构的熊猫数据框:
df = pd.DataFrame({'ID':['A001', 'A001', 'A001', 'A002', 'A002', 'A003', 'A003', 'A004', 'A004', 'A004', 'A005', 'A005'],
'Val1':[2, 2, 2, 5, 6, 8, 8, 3, 3, 3, 7, 7],
'Val2':[100, -100, 50, -40, 40, 60, -50, 10, -10, 10, 15, 15]})
ID Val1 Val2
0 A001 2 100
1 A001 2 -100
2 A001 2 50
3 A002 5 -40
4 A002 6 40
5 A003 8 60
6 A003 8 -50
7 A004 3 10
8 A004 3 -10
9 A004 3 10
10 A005 7 15
11 A005 7 15
我想删除重复行,其中 ID 和 Val1 是重复的,并且 Val2 在两行中总和为零。正/负 Val2 行也可能不连续,即使在groupby
在上述样本数据中,第 0 行和第 1 行以及第 7、8、9 行满足这些条件。我想删除 [0, 1] 和 [7, 8] 或 [8, 9]。
这里的另一个限制是可能存在完全重复的行 ([10, 11])。在这种情况下,我想保留两行。
因此,所需的输出是:
ID Val1 Val2
2 A001 2 50
3 A002 5 -40
4 A002 6 40
5 A003 8 60
6 A003 8 -50
9 A004 3 10
10 A005 7 15
11 A005 7 15
没有遍历每一行并寻找符合标准的其他行,我没有想法找到一种更“pythonic”的方式来做到这一点。任何帮助深表感谢。
解决方案
我在代码中添加了一些注释,所以希望我的思路应该很清楚:
cond = df.assign(temp=df.Val2.abs())
# a way to get the same values (differentiated by their sign)
# to follow each other
cond = cond.sort_values(["ID", "Val1", "temp"])
# cumsum should yield a zero for numbers that are different
# only by their sign
cond["check"] = cond.groupby(["ID", "temp"]).Val2.cumsum()
cond["check"] = np.where(cond.check != 0, np.nan, cond.check)
# the backward fill here allows us to assign an identifier
# to the two values that summed to zero
cond["check"] = cond["check"].bfill(limit=1)
# this is where we implement your other condition
# essentially, it looks for rows that are duplicates
# and rows that any two rows sum to zero
cond.loc[
~(cond.duplicated(["ID", "Val1"], keep=False) & (cond.check == 0)),
["ID", "Val1", "Val2"],
]
ID Val1 Val2
2 A001 2 50
3 A002 5 -40
4 A002 6 40
6 A003 8 -50
5 A003 8 60
9 A004 3 10
推荐阅读
- docker - 连接 nginx 和 php 容器的 Docker 链接
- excel - 使用索引和匹配返回错误:“公式或函数无法使用值”
- laravel - Laravel 覆盖包中的父视图
- android - 尝试访问 PlacesClient.findCurrentPlace() 时出现 com.android.volley.TimeoutError
- python - 使用线程python将参数从一个类传递到另一个类
- swift - 在 Swift 函数中,当函数在循环内包含带有 if 语句的 for 循环时,为什么“return”必须在 for 循环之外?
- javascript - 如何使用复制到剪贴板
- r - 函数正在为无效参数执行
- keras - 为什么 YOLO v3 Keras 越野车?
- c# - 通过 XAML 将 Windows Accent Color 设置为 WPF 窗口背景并监听 Accent Color Change