【问题标题】:Keeps rows that aren't in list保留不在列表中的行
【发布时间】:2021-08-09 17:38:42
【问题描述】:

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

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

【问题讨论】:

  • 我不明白你的描述。 df.loc 不会删除任何内容。我们只能告诉您您实际向我们展示的代码有什么问题。
  • 它在我身边工作df.loc[~(df.offer.isin(remove_these_offers_list))]
  • 所以当你运行它时,你会得到一个数据框,其中包含“苹果和三星 10 英镑的折扣”。 isin 不能通过部分字符串匹配工作吗?
  • isin 始终适用于完全匹配,而 str.contains 适用于部分匹配(但您也可以通过在模式中添加单词边界使其像完全匹配一样工作)
  • @Anurag 抱歉,我现在才看到你的评论。

标签: python python-3.x pandas isin


【解决方案1】:

尝试使用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

【讨论】:

    【解决方案2】:

    你可以这样做:

    df[~df['offer'].isin(remove_these_offers_list)]
    

    isin 应该适用于列表,而不是包含的字符串,因此只有完全匹配才有效

    【讨论】:

      猜你喜欢
      • 2020-04-05
      • 1970-01-01
      • 1970-01-01
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 2020-10-21
      • 2015-02-17
      • 2012-05-10
      相关资源
      最近更新 更多