首页 > 解决方案 > 删除在 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”的方式来做到这一点。任何帮助深表感谢。

标签: pythonpandas

解决方案


我在代码中添加了一些注释,所以希望我的思路应该很清楚:

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

推荐阅读