首页 > 解决方案 > 保留不在列表中的行

问题描述

我有一个包含销售和优惠的数据框。

df  offer                       sales
0   £10 off appple               10
1   £10 off apple and samsung    20

我有一个我想避免的报价列表,在这个例子中只有 1 个报价。

remove_these_offers_list = ["£10 off appple"]

当我尝试使用删除此优惠时, df.loc[~(df.offer.isin(remove_these_offers_list))] 我得到一个空的 df,因为从技术上讲,该字符串包含在两行中。

预期产出

df  offer                        sales
1   £10 off apple and samsung     20

标签: pythonpython-3.xpandasisin

解决方案


尝试使用以下方法去除空白str.strip()

df=df.loc[~(df['offer'].str.strip().isin(remove_these_offers_list))]

或者

由于您提到的方法正在以另一种方式通过str.fullmatch()

df=df.loc[~df['offer'].str.fullmatch('|'.join(remove_these_offers_list))]

输出df

    df  offer                       sales
1   1   £10 off apple and samsung   20

推荐阅读