How to change all negative values in dataframe(pandas) to NaN values?

112 Views Asked by At

I have a dataframe with 4 numerical columns and 1 column with string values. One of the columns contains several negative values which I need to replace with NaN value.

I've tried mask method df.mask(df_iris_new < 0), but the error was that I can't compare str and int,

so I tried:

df.mask(df_iris_new['column1'] < 0)

and then it replaced the whole row with NaN values, whereas I need to change only this particular negative value from the first column, as all the rest are positive values that I need.

And the other question is should I somehow exclude the string column from the method?

2

There are 2 best solutions below

0
Ynjxsjmh On BEST ANSWER

You can use DataFrame.select_dtypes to find the numeric columns

cols = df.select_dtypes(include='number').columns
df[cols] = df[cols].mask(df[cols] < 0)
1
SomeDude On

If you are sure there is one column with string and you know the column name, then you can do:

numeric_cols = df.columns.difference(['string_col'])
df[numeric_cols] = df[numeric_cols].mask(df[numeric_cols].lt(0))