python - Relabel levels in pandas -


in pandas dataframe i'm trying relabel 2 levels of variable 1 single name leave 'nan' values in variable untouched.

below reproducible example using modified version of 'mtcars' dataset. here want relabel 'yes' , 'no' levels of 'am' variable 'new' example.

                    mpg   cyl  disp  hp drat    wt  qsec vs    mazda rx4           21.0  6 160.0 110 3.90 2.620 16.46  0  yes      mazda rx4 wag       21.0  2 160.0 110 3.90 2.875 17.02  0  nan     datsun 710          22.8  6 108.0  93 3.85 2.320 18.61  1  no     hornet 4 drive      21.4  2 258.0 110 3.08 3.215 19.44  1  nan    hornet sportabout   18.7  6 360.0 175 3.15 3.440 17.02  0  yes   valiant             18.1  2 225.0 105 2.76 3.460 20.22  1  nan    duster 360          14.3  2 360.0 245 3.21 3.570 15.84  0  no    

result this:

                    mpg   cyl  disp  hp drat    wt  qsec vs    mazda rx4           21.0  6 160.0 110 3.90 2.620 16.46  0  new      mazda rx4 wag       21.0  2 160.0 110 3.90 2.875 17.02  0  nan     datsun 710          22.8  6 108.0  93 3.85 2.320 18.61  1  new     hornet 4 drive      21.4  2 258.0 110 3.08 3.215 19.44  1  nan    hornet sportabout   18.7  6 360.0 175 3.15 3.440 17.02  0  new   valiant             18.1  2 225.0 105 2.76 3.460 20.22  1  nan    duster 360          14.3  2 360.0 245 3.21 3.570 15.84  0  new 

try:

  mt['am'] = mt.am.map(lambda x: x if pd.isnull(x) else 'new') 

output:

in [21]: df = pd.dataframe(['yes',np.nan,'no',np.nan], columns=['am'])  in [22]: df out[22]:      0  yes 1  nan 2   no 3  nan  in [23]: df['am'] = df.am.map(lambda x: x if pd.isnull(x) else 'new')  in [24]: df out[24]:      0  new 1  nan 2  new 3  nan 

Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -