求助排查AttributeError:DataFrame对象无'Genre'属性问题
AttributeError: 'DataFrame' object has no attribute 'Genre' 问题分析与解决
错误信息
Traceback (most recent call last): File "/Users/anishchowdary/Couch to Coder/Week 4/using_pandas.py", line 10, in <module> print(number_of_books_written.Genre) File "/Users/anishchowdary/PycharmProjects/ISAconverter/venv/lib/python3.9/site-packages/pandas/core/generic.py", line 6202, in __getattr__ return object.__getattribute__(self, name) AttributeError: 'DataFrame' object has no attribute 'Genre'
问题成因
执行sellers.groupby('Genre')[['Name']].count()时,Genre会被自动设为DataFrame的索引,而非普通列。此时number_of_books_written里不存在名为Genre的列,自然无法通过.Genre的方式访问。
解决办法
有两种常用修复方式:
方式1:分组时保留Genre为列
在groupby中添加as_index=False参数,让分组键保持为列而非索引:
import pandas as pd import matplotlib.pyplot as plt bestsellers = pd.read_csv("bestsellers with categories.csv") sellers = bestsellers.drop_duplicates(subset='Name', keep='last') # 添加as_index=False,Genre会作为普通列存在 number_of_books_written = sellers.groupby('Genre', as_index=False)[['Name']].count().sort_values("Name", ascending=False).head(10) print(number_of_books_written.Genre)
方式2:将索引转回列
如果已生成目标DataFrame,可通过reset_index()把索引转换为列:
import pandas as pd import matplotlib.pyplot as plt bestsellers = pd.read_csv("bestsellers with categories.csv") sellers = bestsellers.drop_duplicates(subset='Name', keep='last') number_of_books_written = sellers.groupby('Genre')[['Name']].count().sort_values("Name", ascending=False).head(10) # 重置索引,把Genre转回列 number_of_books_written = number_of_books_written.reset_index() print(number_of_books_written.Genre)
额外说明:直接访问索引
若仅需查看Genre的取值,也可直接访问DataFrame的索引:
print(number_of_books_written.index)
内容的提问来源于stack exchange,提问作者twoinchpeepee
相关产品推荐
相关产品推荐

