问题来源:做项目时,想拿到不符合条件的所有数据,比如:通话类型有好多种(主叫、被叫、呼转……),现在想分析所有非主叫数据,那么问题就来了。
方法一:df[~df.col.str.contains(word)]- 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]- 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
复制代码 多个条件情况下:- 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('意见')))]
复制代码 方法三:- df = pd.DataFrame({"A": ["Hello", "this", "World", "apple"]})df['A'].str.contains(r'^(?:(?!Hello|World).)*$')Name: A, dtype: bool0 False1 True2 False3 True
复制代码- df[df['A'].str.contains(r'^(?:(?!Hello|World).)*$')] A1 this3 apple
复制代码 比较df.col.str.contains 和 df.col.isin([‘a’,‘b’])
后者不是匹配,而是字符串等于a,或者b
|
|