Reputation: 33
I am trying to map a column in my dataframe from [Yes, No] to [1,0] without having to create multiple variable dummy columns. I did using:
df['A'] = df.A.map({'Yes':1, 'No': 0})
where df is the dataframe and A is a column in the dataframe. It worked, However I have several columns I'll like to map, so I created a function.
def mapping(df, column_name):
mapped = df.column_name.map({'Yes':1, 'No':1})
df = df.replace(column_name, mapped)
return df
There was no objection in the jupyter notebook, it ran. but when I called the function and inserted my values like
mapping(df, B)
I get the following error:
'AttributeError: 'DataFrame' object has no attribute 'column_name''
How do i solve this please?
Upvotes: 0
Views: 2541
Reputation: 26
The statement that is causing the error is ;
mapped = df.column_name.map({'Yes':1, 'No':1})
In pandas, this line tries to access the column named 'column_name'. That means, this does not take the string stored in the variable 'column_name' but instead takes 'column_name' as a string and tries to find the attribute called 'column_name'.
Instead, you can use the statement;
mapped = df[column_name].map({'Yes':1, 'No':1})
Upvotes: 1