简体   繁体   English

如果包含条件,则删除 pandas 中的行

[英]Drop row in pandas if it contains condition

I am trying to drop rows in pandas based on whether or not it contains "/" in the cells in column "Price".我正在尝试根据“价格”列中的单元格中是否包含“/”来删除 pandas 中的行。 I have referred to the question: Drop rows in pandas if they contains "???"我提到了这个问题: 如果 pandas 中包含“???”,则删除行. .

As such, I have tried both codes:因此,我尝试了两种代码:

df = df[~df["Price"].str.contains('/')]

and

df = df[~df["Price"].str.contains('/',regex=False)]

However, both codes give the error: AttributeError: Can only use.str accessor with string values!但是,两个代码都给出了错误: AttributeError: Can only use.str accessor with string values!

For reference, the first few rows of my dataframe is as follows:作为参考,我的dataframe的前几行如下:

    Fruit   Price
0   Apple     3
1   Apple    2/3
2   Banana    2
3   Orange   6/7

May I know what went wrong and how can I fix this problem?我可以知道出了什么问题,我该如何解决这个问题? Thank you very much!非常感谢!

Try this:尝试这个:

df = df[~df['Price'].astype(str).str.contains('/')]
print(df)

    Fruit Price
0   Apple     3
2  Banana     2

You need to convert the price column to string first and then apply this operation.您需要先将价格列转换为字符串,然后再应用此操作。 I believe that price column doesn't have datatype string我相信价格列没有数据类型字符串

df['Price'] = df['Price'].astype(str)

and then try然后尝试

df = df[~df["Price"].str.contains('/',regex=False)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM