使用Seaborn绘制分组柱状图时groupby后Series属性错误如何修正
问题原因
你报错的核心原因是 groupby('Last_region')['Customer_Value'].sum() 返回的是带索引的Series对象,Last_region 会作为这个Series的索引存在,不会作为普通列保留,自然无法通过 .Last_region 调用。
另外原有代码里的 plt.show 少了括号,属于语法疏漏,也会导致图像无法正常弹出。
修复方案
- 方案1:分组时保留分组列为普通列,得到DataFrame(最常用,后续字段调用更直观)
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt customer = pd.read_csv('D:\PythonTraining\Customer.csv') # 新增as_index=False,让Last_region保留为普通列,返回结果为DataFrame df = customer.groupby('Last_region', as_index=False)['Customer_Value'].sum() sns.barplot(x = df.Last_region, y = df.Customer_Value) plt.show() # 补全括号
- 方案2:直接使用现有Series的索引和值绘图,无需转换格式
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt customer = pd.read_csv('D:\PythonTraining\Customer.csv') df = customer.groupby('Last_region')['Customer_Value'].sum() # 直接取Series的索引作为x轴,值作为y轴 sns.barplot(x = df.index, y = df.values) plt.show()
内容的提问来源于stack exchange,提问作者user1902849
相关产品推荐
相关产品推荐

