0

I am trying to drop rows in pandas based on whether or not it contains "/" in the cells in column "Price". I have referred to the question: Drop rows in pandas if they contains "???".

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!

For reference, the first few rows of my dataframe is as follows:

 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!

4
  • 1
    what is the data type of Price, is it str? Commented Jun 17, 2020 at 17:05
  • Call dtype and see what's its dtype and try casting to string if its not a string using astype Commented Jun 17, 2020 at 17:09
  • Oh it is an object. I've tried to use astype but it's still an object Commented Jun 17, 2020 at 17:09
  • object is ok. I think this column have NaN values Commented Jun 17, 2020 at 17:13

2 Answers 2

1

Try this:

df = df[~df['Price'].astype(str).str.contains('/')] print(df) Fruit Price 0 Apple 3 2 Banana 2 
Sign up to request clarification or add additional context in comments.

Comments

1

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)] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.