Yash Sarawgi
Yash Sarawgi

Reputation: 21

AttributeError: 'int' object has no attribute 'map'

I have a function as defined below:

def season_map(x):
    return x.map({1:'spring',2:'summer',3:'fall',4:'winter'})

Now on calling the function on season column which only contains values 1, 2, 3 or 4:

bike_data['season'] = bike_data['season'].apply(season_map)

The error given is: AttributeError: 'int' object has no attribute 'map'

But if I try:

bike_data['season'] = bike_data['season'].map({1:'spring',2:'summer',3:'fall',4:'winter'})

It works perfectly!

Unable to understand what is the difference in the 2 approaches apart from syntax....

Upvotes: 2

Views: 2493

Answers (2)

Pravan Pinto
Pravan Pinto

Reputation: 11

My first answer/post. I was solving this problem today. The answer is you need to pass the particular column as a list:

    def season_map(x):
        return x.map({1:'spring',2:'summer',3:'fall',4:'winter'})
    bike_data[['season']] = bike_data[['season']].apply(season_map)

Upvotes: 1

Roelant
Roelant

Reputation: 5119

The map function gets the integer, but has a map as well. Probably just a copy paste error.

Try

def season_map(x):
    return {1:'spring', 2:'summer', 3:'fall', 4:'winter'}[x]

Or easier

season_map = {1:'spring', 2:'summer', 3:'fall', 4:'winter'}
bike_data['season'] = bike_data['season'].map(season_map)

Upvotes: 0

Related Questions