pandas 获取不符合条件/不包含某个字符串的dataframe

pandas 获取不符合条件/不包含某个字符串的dataframe

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

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

 ~df.A.str.contains("Hello|World")
False
True
False
True
Name: A, dtype: bool

 df[~df.A.str.contains("Hello|World")]
A
this
apple
[2 rows x 1 columns]

note

  • 似乎 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[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]
or
data[~((data.title.str.contains('公告'))  |(data.title.str.contains('意见')))]

方法三:

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

原文:https://blog.csdn.net/chihwei_hsu/article/details/81604455

比较df.col.str.contains 和 df.col.isin([‘a’,‘b’])
后者不是匹配,而是字符串等于a,或者b

  • 13
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值