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

论坛 期权论坛 期权     
编程开发爱好者   2019-7-21 15:26   12020   0
问题来源:做项目时,想拿到不符合条件的所有数据,比如:通话类型有好多种(主叫、被叫、呼转……),现在想分析所有非主叫数据,那么问题就来了。
方法一:df[~df.col.str.contains(word)]
  1. df = pd.DataFrame({"A": ["Hello", "this", "World", "apple"]})df.A.str.contains("Hello|World")TrueFalseTrueFalseName: A, dtype: bool ~df.A.str.contains("Hello|World")FalseTrueFalseTrueName: A, dtype: bool df[~df.A.str.contains("Hello|World")]Athisapple[2 rows x 1 columns]
复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
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]
  1. df[df["col"].str.contains('this'|'that')==False]df = pd.DataFrame({"A": ["Hello", "this", "World", "apple"]})df[df['A'].str.contains("Hello|World")==False]A1   this3  apple
复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
多个条件情况下:
  1. df[df["col1"].str.contains('this|that')==False and df["col2"].str.contains('foo|bar')==True]ordata[~((data.title.str.contains('公告'))  |(data.title.str.contains('意见')))]
复制代码
  • 1
  • 2
  • 3
方法三:
  1. df = pd.DataFrame({"A": ["Hello", "this", "World", "apple"]})df['A'].str.contains(r'^(?:(?!Hello|World).)*$')Name: A, dtype: bool0    False1     True2    False3     True
复制代码
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  1. df[df['A'].str.contains(r'^(?:(?!Hello|World).)*$')]    A1   this3  apple
复制代码
  • 1
  • 2
  • 3
  • 4
比较df.col.str.contains 和 df.col.isin([‘a’,‘b’])
后者不是匹配,而是字符串等于a,或者b
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:10
帖子:2
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP