1

I have a df with a column that I want to filter for only negative or only positve values,

when I try code below as:

df.loc[df['values'] > 0]

I get error of

`TypeError: '>' not supported between instances of 'str' and 'int'

I try to convert the object data type of the values column to integer:

df['values'].astype(str).astype(int) 

I get error of : ValueError: invalid literal for int() with base 10: '3.69'

Thanks!

How Can I convert correctly so I can then filter correctly? Thanks!

1
  • 2
    convert it to float (3.69 is a float) Commented Nov 2, 2020 at 20:42

2 Answers 2

2

You need to convert it to a float dtype since 3.69 is a decimal (and therefore a float). int datatypes can only non-decimal numbers (e.g. 1, 2, 4, 100, 900). Try this:

df.loc[df['values'].astype(float) > 0]
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to convert it to int you should use apply function:

df = df.assign(values = lambda x: x['values'].apply(lambda s: int(s))) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.