Search code examples
pandasdataframe

Conditional mapping in pandas


I am trying to map values of my columns. For gender the following mapping works:

df['gender'] = df['gender'].map({'female': 0, 'male': 1, 'other': 2})

Similarly I would like to map age column based on the range they belong to, so that, each decade is a separate class. Here is my not working code:

   df['age'] = df['age'].map({
                              '25 < age < 36': 1,
                              '35 < age < 46': 2,
                              '45 < age < 56': 3
                             })
   

How can I do the mapping correctly? Thanks in advance.


Solution

  • A possible solution, which is base on numpy.where:

    np.where((df['age'] > 25) & (df['age'] < 36), 1, 
             np.where((df['age'] > 35) & (df['age'] < 46), 2, 
                      np.where((df['age'] > 45) & (df['age'] < 56), 3, 0)))