搜索“不包含"在 Pandas 的 DataFrame 上 [英] Search for "does-not-contain" on a DataFrame in pandas

查看:55
本文介绍了搜索“不包含"在 Pandas 的 DataFrame 上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我进行了一些搜索,但不知道如何通过 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?

推荐答案

您可以使用反转 (~) 运算符(对于布尔数据,它的作用类似于 not):

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.

contains 也接受正则表达式...

如果上面抛出一个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 上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆