问题描述
我已经进行了一些搜索,但无法弄清楚如何使用df["col"].str.contains(word)
过滤数据帧,但是我想知道是否有相反的方法:通过该集合的补充来过滤数据帧.例如:!(df["col"].str.contains(word))
的效果.
I've done some searching and can't figure out how to filter a dataframe by df["col"].str.contains(word)
, however I'm wondering if there is a way to do the reverse: filter a dataframe by that set's compliment. eg: to the effect of !(df["col"].str.contains(word))
.
这可以通过DataFrame
方法完成吗?
Can this be done through a DataFrame
method?
推荐答案
您可以使用invert(〜)运算符(其作用类似于非布尔数据):
You can use the invert (~) operator (which acts like a not for boolean data):
new_df = df[~df["col"].str.contains(word)]
,其中new_df
是RHS返回的副本.
, where new_df
is the copy returned by RHS.
还包含一个正则表达式...
如果上面的方法抛出ValueError,则可能是由于您混合了数据类型,所以请使用na=False
:
If the above throws a ValueError, the reason is likely because you have mixed datatypes, so use na=False
:
new_df = df[~df["col"].str.contains(word, na=False)]
或者,
new_df = df[df["col"].str.contains(word) == False]
这篇关于搜索“不包含";在 pandas 的DataFrame上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!