【问题标题】:Drop with condition [duplicate]有条件的删除[重复]
【发布时间】:2018-09-24 15:27:55
【问题描述】:

我想从 df1 中删除某些行。我确实以这种方式编写了条件,并向我展示了我想要删除的确切行。但是,当我尝试对这些数据应用 drop 时,它不起作用:

to_be deleted = df1.loc[df1['barcode'].str.contains('....-..-....-11.', regex=True)]

当我使用时

to_be deleted.head()
print(len(to_be deleted))

我可以看到我要删除的数据,这意味着代码有效。 但是,当我尝试删除这些行时,它不起作用

df2 = df1.drop([df1['barcode'].str.contains('....-..-....-11.', regex=True)], axis=1, inplace=True)

我也试过了

df2 = df1.drop(to_be_deleted, axis=1, inplace=True)

但它要么显示:

'Series' objects are mutable, thus they cannot be hashed

/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py:1: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

如何删除我在 (to_be_deleted) 数据框中指定的这些行?

谢谢

【问题讨论】:

  • 链接问题中的第二个答案可能是您正在寻找的。​​span>

标签: python python-3.x pandas


【解决方案1】:

您不需要为此使用pd.DataFrame.drop

mask = df1['barcode'].str.contains('....-..-....-11.', regex=True)

df1 = df1[~mask]

~ 运算符表示否定。由于mask 是一个布尔数组,它被取反并用作df1 上的行过滤器。

【讨论】:

  • 哦,非常感谢。现在可以使用了。
猜你喜欢
  • 1970-01-01
  • 2015-11-18
  • 2019-02-02
  • 2022-11-10
  • 2018-02-17
  • 2015-07-12
  • 1970-01-01
  • 2012-06-05
  • 2020-07-03
相关资源
最近更新 更多