的要求是使用seaborn庫來繪制一個條形圖,示出了銷售總額(Customer_Value)由Last_region。這是我的代碼
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()
df
sns.barplot(x = df.Last_region, y = df.Customer_Value)
plt.show
我收到一個錯誤:
AttributeError: 'Series' 物件沒有屬性 'Last_region'。
我該如何糾正?我相信在groupby之后,該屬性不能被參考。
uj5u.com熱心網友回復:
問題是Last_region當您對其進行分組時,它會成為索引。另請注意,df這里很可能是一個系列,而不是一個 DataFrame,在這種情況下Customer_Value也不會是一個列。
要么使用
x=df.index和y=df.valuessns.barplot(x=df.index, y=df.values)或使用
data=df.reset_index()(現在保證是帶有這些列的 DataFrame)sns.barplot(data=df.reset_index(), x='Last_region', y='Customer_Value')
或者,正如 Asish 評論的那樣,您可以進行更改df,使其Last_region不是索引:
as_index=False分組時設定df = customer.groupby('Last_region', as_index=False)['Customer_Value'].sum()或者
reset_index()分組后df = customer.groupby('Last_region')['Customer_Value'].sum().reset_index()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/349876.html
