简体   繁体   中英

How do I solve 'DataFrame' object has no attribute 'column_name'?

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?

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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM