mardi 2 octobre 2018

Creating New Column Using IF and Apply Function

My Age data is float and I want to create a new categorical column with three values: Elder, Child and Adult. I defined a function and added iloc[0] to iterate individual values in existing df['Age'] column. However, my result always 'Elder' with one unique result.

def ages(a):          
   if ((df['Age'].iloc[0])>50):  
      return 'Elder'  
   elif ((df['Age'].iloc[0])<12):  
      return 'Child'  
   elif (df['Age'].iloc[0]<50) & (df['Age'].iloc[0]>12):  
      return 'Adult'  

df['Agem']=df['Age'].apply(ages)

Aucun commentaire:

Enregistrer un commentaire