0

I'm, trying to to add a new column to my df that will be mapped by ranges of other column in the same df. I'm using pandas.series.between() function to define the new values but getting an error: TypeError: unhashable type: 'Series'

This is what I have tried:

my_dict = {df['column'].between(0.0, 5.0) : 1,
                  df['column'].between(5.1, 7.0) : 2,
                  df['column'].between(7.1, 10.0) : 3,
                  df['column'].between(10.1, 13.0) : 4,
                  df['column'].between(13.1, 16.0) : 5,
                  df['column'].between(19.1, 22.0) : 6,
                  df['column'].between(22.1, 25.0) : 7,
                  df['column'].between(25.1, 28.0) : 8,
                  df['column'].between(28.1, 31.0) : 9,
                  df['column'].between(31.1, 34.0) : 10,
                  df['column'].between(34.1, 37.0) : 11,
                  df['column'].between(37.1, 40.0) : 12,
                  df['column'].between(40.1, df['column'].max()) : 13
                 }


df['new_column'] = df.map(my_dict)

If there's any other way to do that without s.bewtween() it will be also a good option.

Ofir
  • 101
  • 3

1 Answers1

0

We can directly use df.apply

def map_function(x):
   if 0.0<= x <=5        : return 1
   elif 5.1<=x<=7.0      : return 2
   elif 7.1<= x <=10.0   : return 3
   elif 10.1<= x <=13.0  : return 4
   elif 13.1<=x <= 16.0  : return 5
   elif 16.1<=x<=19.0    :return  6
   elif 19.1<=x<=22.0    :return  7
   elif 22.1<=x<=25.0    :return  8
   elif 25.1<=x<=28.0    :return  9
   elif 28.1<=x<=31.0    :return  10
   elif 31.1<=x<=34.0    :return  11
   elif 34.1<=x<=37.0    :return  12
   elif 37.1<= x <=40.0  :return  13
   elif x >40.0: return 14
df['new_column']=df['column'].apply(map_function)

Note : In the ranges you mentioned, you missed a bracket -(16-19)elif 16.1<=x<=19.0 :return 6 Assuming that it was bymistake I took liberty to add that range.
If Missing the range(16-19) was intentional then make changes accordingly for the map_function.