Home > database >  Converting negative values in dataframe to NaN
Converting negative values in dataframe to NaN

Time:11-06

I have a dataframe that has negative values. I would like to replace the negative values to NaN. The dataframe contains different column types (Object, float, int..) and has over 15 numeric columns so I am looking for a solution that would identify the numeric columns then change the negative values to NaN.

name                sodium   potass    .....
Natural Bran         130      280      .....
All-Bran             -1       330      .....
Almond Delight      200       -5       .....
Tex                 120       -2       ..... 

Thank you

CodePudding user response:

Using pandas.mask could solve your problem.

df = df.mask(df < 0) # default replaced value is nan when the condition is fulfilled.

CodePudding user response:

This also works

import numpy as np

df[df < 0] = np.nan

if you want to make changes in particular cols

df[df['sodium'] < 0] = np.nan
  • Related