Pandas replace values in a mixed datatype column

Question:

I have a dataframe, that has a column ‘A1’ that contains strings, postive as well as negative integers. I want to replace the all integers >= 0 with True and everyting else with false (strings, neg. int, etc.)

My DataFrame looks like this:

index A1
0 1
1 Hello
2 -8
3 Hello

and shall look like this:

index A1
0 True
1 False
2 False
3 False

I tried it this way, but then I drop all other columns:

df= pd.DataFrame(pd.to_numeric(df['A1'], errors="coerce").agg(lambda x: x.ge(0)))

How can I do this so the rest of the DataFrame is kept?

Asked By: Petra Enis

||

Answers:

Use:

df = df.assign(A1 = pd.to_numeric(df['A1'], errors="coerce").ge(0))

Or:

df['A1'] = pd.to_numeric(df['A1'], errors="coerce").ge(0)
Answered By: jezrael
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.