samedi 29 avril 2017

Nested if using lambda in Python

I have a dataset like this:

Build_year Max_cnt_year   b1920  b1945 b1975 b1995 
NaN        120            120    35    45    70    
0          67             35     67    21    34    
1921       145            39     67    22    145   
...

Desired output:

Build_year Max_cnt_year   b1920  b1945 b1975 b1995 year_build1
NaN        120            120    35    45    70    1920
0          67             35     67    21    34    1945
1921       145            39     67    22    145   1921
...

I want to compare the max_cnt_year against the values of b1920, b1945, b1975, b1995 and want to assign the values accordingly if it matches to that year ,conditional on Build_year>1500

I am trying this code unsuccessfully:

df_all['build_year1'] = df_all.map( lambda x: df_all['build_year'] if df_all['build_year']>1500 
      else( 
      '1920' if df_all['max_cnt_year']==df_all['b1920'] 
      else(
            '1945' if df_all['max_cnt_year']==df_all['b1945']  
      else(
            '1975' if df_all['max_cnt_year']==df_all['b1975']
      else(
            '1995' if df_all['max_cnt_year']==df_all['b1995']
      else '2005'
          ))))

Aucun commentaire:

Enregistrer un commentaire