[英]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.我正在尝试 map 在我的 dataframe 中从 [Yes, No] 到 [1,0] 列,而无需创建多个可变虚拟列。 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.其中 df 是 dataframe 和 A 是 dataframe 中的列。 It worked, However I have several columns I'll like to map, so I created a function.它有效,但是我有几列我想 map,所以我创建了一个 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. jupyter notebook里没有异议,就跑了。 but when I called the function and inserted my values like但是当我调用 function 并插入我的值时
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'.在 pandas 中,此行尝试访问名为“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'.这意味着,这不会获取存储在变量“column_name”中的字符串,而是将“column_name”作为字符串并尝试查找名为“column_name”的属性。
Instead, you can use the statement;相反,您可以使用该语句;
mapped = df[column_name].map({'Yes':1, 'No':1})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.