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