pandas 获取不符合条件的dataframe

本文介绍如何在Pandas DataFrame中筛选出不包含特定字符串的数据行。提供了三种方法:使用str.contains结合逻辑非操作符、直接在DataFrame中进行条件判断以及使用正则表达式进行匹配。适用于数据分析和数据预处理等场景。

search for “does-not-contain” on a dataframe in pandas

问题来源:做项目时,想拿到不符合条件的所有数据,比如:通话类型有好多种(主叫、被叫、呼转……),现在想分析所有非主叫数据,那么问题就来了。

方法一:df[~df.col.str.contains(word)]

>>> df = pd.DataFrame({"A": ["Hello", "this", "World", "apple"]})
>>> df.A.str.contains("Hello|World")
0     True
1    False
2     True
3    False
Name: A, dtype: bool
>>> ~df.A.str.contains("Hello|World")
0    False
1     True
2    False
3     True
Name: A, dtype: bool
>>> df[~df.A.str.contains("Hello|World")]
       A
1   this
3  apple

[2 rows x 1 columns]

注意:
- 似乎 df[~(df.A.str.contains("Hello") | (df.A.str.contains("World")))]比上面使用正则,速度会快点
- 获取“非”数据的条数:(~df.col3.str.contains('u|z')).sum()

方法二:

df[df["col"].str.contains('this'|'that')==False]
>>> df = pd.DataFrame({"A": ["Hello", "this", "World", "apple"]})
>>> df[df['A'].str.contains("Hello|World")==False]
       A
1   this
3  apple

# 多个条件情况下:
# df[df["col1"].str.contains('this|that')==False and df["col2"].str.contains('foo|bar')==True]

方法三:

>>> df = pd.DataFrame({"A": ["Hello", "this", "World", "apple"]})
>>> df['A'].str.contains(r'^(?:(?!Hello|World).)*$')
0    False
1     True
2    False
3     True
Name: A, dtype: bool
>>> df[df['A'].str.contains(r'^(?:(?!Hello|World).)*$')]
       A
1   this
3  apple

作者:Chihwei_hsu
来源:http://chihweihsu.com
Github:https://github.com/HsuChihwei

评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值