Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas replace multiple columns zero to Nan

List with attributes of persons loaded into pandas dataframe df2. For cleanup I want to replace value zero (0 or '0') by np.nan.

df2.dtypes  ID                   object Name                 object Weight              float64 Height              float64 BootSize             object SuitSize             object Type                 object dtype: object 

Working code to set value zero to np.nan:

df2.loc[df2['Weight'] == 0,'Weight'] = np.nan df2.loc[df2['Height'] == 0,'Height'] = np.nan df2.loc[df2['BootSize'] == '0','BootSize'] = np.nan df2.loc[df2['SuitSize'] == '0','SuitSize'] = np.nan 

Believe this can be done in a similar/shorter way:

df2[["Weight","Height","BootSize","SuitSize"]].astype(str).replace('0',np.nan) 

However the above does not work. The zero's remain in df2. How to tackle this?

like image 922
Wouter Dunnes Avatar asked Jul 31 '17 13:07

Wouter Dunnes


People also ask

How do I replace values in multiple columns in pandas?

Pandas replace multiple values in column replace. By using DataFrame. replace() method we will replace multiple values with multiple new strings or text for an individual DataFrame column. This method searches the entire Pandas DataFrame and replaces every specified value.

How do you replace NaN with 0 for multiple columns in Python?

You can also use df. replace(np. nan,0) to replace all NaN values with zero. This replaces all columns of DataFrame with zero for Nan values.


1 Answers

I think you need replace by dict:

cols = ["Weight","Height","BootSize","SuitSize","Type"] df2[cols] = df2[cols].replace({'0':np.nan, 0:np.nan}) 
like image 186
jezrael Avatar answered Sep 20 '22 02:09

jezrael