Reputation: 5
In the above dataframe I am trying to replace NaN and negative values in the last column with 0 using pandas, I have used some of the suggestions here, but it also seems to affect other columns and replace values in the other columns with zeroes.
How do I restrict it to just the selected column
Upvotes: 0
Views: 3047
Reputation: 23217
You can use .mask()
to change negative numbers to NaN
and then fillna()
to 0
together with other NaN
values in one go, as follows:
df['New_expenses'] = df['New_expenses'].mask(df['New_expenses'] < 0).fillna(0)
Or, even more simpler, credit to @tdy, using .where()
instead:
df['New_expenses'] = df['New_expenses'].where(df['New_expenses'] >= 0, 0)
.where()
keeps the values when the condition is true and replaces values when the condition is false.
In this case, we keeps the values when the values are positive and replaces the values to 0
when the condition is false (including negative numbers and NaN
values).
Upvotes: 3
Reputation: 260600
Use clip
to set the negative values to a minimum, and fillna
to replace the NAs:
df['New_expenses'] = df['New_expenses'].clip(lower=0).fillna(0)
Upvotes: 2