使用 Seaborn 库绘制条形图并按功能分组
Plot a bar chart with Seaborn library and group by function
要求是使用 seaborn 库绘制条形图,显示 Last_region
的总销售额 (Customer_Value
)。这是我的代码
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' object has no attribute 'Last_region'.
如何更正?我相信在groupby之后,该属性不能被引用。
问题是 Last_region
在您分组时成为索引。另请注意,这里的 df
很可能是一个系列,而不是 DataFrame,在这种情况下 Customer_Value
也不是一列。
使用x=df.index
和y=df.values
sns.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()
要求是使用 seaborn 库绘制条形图,显示 Last_region
的总销售额 (Customer_Value
)。这是我的代码
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' object has no attribute 'Last_region'.
如何更正?我相信在groupby之后,该属性不能被引用。
问题是 Last_region
在您分组时成为索引。另请注意,这里的 df
很可能是一个系列,而不是 DataFrame,在这种情况下 Customer_Value
也不是一列。
使用
x=df.index
和y=df.values
sns.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()