python - 从数据中排除 2 个字符串

标签 python regex pandas

我有关于 3 种水果及其数量的数据。我想从我的数据中排除“Apple”和“Pear”,但遇到以下错误。为什么会这样?

import pandas as pd

df=(pd.DataFrame({'Fruit':['Apple','Orange','Pear','Apple','Orange']
                    ,'Qty':[3,4,1,7,9]}))


df=df[df['Fruit'].str.contains('Apple'|'Pear')==False]
print(df)

TypeError: unsupported operand type(s) for |: 'str' and 'str'

最佳答案

| 运算符应该在字符串本身中:

df[df['Fruit'].str.contains('Apple|Pear')==False]

或者,使用否定运算符:

df[~df['Fruit'].str.contains('Apple|Pear')]
Out: 
    Fruit  Qty
1  Orange    4
4  Orange    9

关于python - 从数据中排除 2 个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43435071/

相关文章:

python - 如何绘制并排分组条形图

python - pandas Series.value_counts 返回相等计数字符串的不一致顺序

python - Pandas:数据帧到面板错误:NotImplementedError:仅支持 2 级 MultiIndex

python - 我需要将 virtualenv 与 Vagrant 一起使用吗?

python - 迭代 n 个值

python - 在 virtualenv 内部安装 M2Crypto,而不在系统中安装 swig

c# - 使用正则表达式匹配带引号和不带引号的字符串

python - 我想使用 IronPython 绘制 visio 图

mysql - SQL中的正则表达式检测一个或多个数字

regex - 当 [ :punct:] is too much