Python 使用CSV文件创建条形图,显示城市每年哪个月的平均销售额最高

Python 使用CSV文件创建条形图,显示城市每年哪个月的平均销售额最高,python,pandas,jupyter-notebook,Python,Pandas,Jupyter Notebook,报纸上的问题是:“用条形图的方式——按年份平均显示最忙的月份 在爱丁堡市的销售量,条形图应该有12个条形, 每月一次,总销售额应为该月的平均销售额 每年可用数据的月份。” 因此,这里是数据帧的一个小表示。注意:原始数据帧非常大,有许多列和行,因此,这只是原始数据帧的缩小版本 import pandas as pd df = pd.DataFrame({'Date': ['01/07/2020','01/08/2020','01/09/2020','01/10/2020','01/11/2020'

报纸上的问题是:“用条形图的方式——按年份平均显示最忙的月份 在爱丁堡市的销售量,条形图应该有12个条形, 每月一次,总销售额应为该月的平均销售额 每年可用数据的月份。”

因此,这里是数据帧的一个小表示。注意:原始数据帧非常大,有许多列和行,因此,这只是原始数据帧的缩小版本

import pandas as pd
df = pd.DataFrame({'Date': ['01/07/2020','01/08/2020','01/09/2020','01/10/2020','01/11/2020','01/12/2020','01/01/2021','01/01/2004','01/02/2004','01/03/2004','01/04/2004','01/05/2004','01/06/2004','01/07/2004','01/08/2004','01/09/2004','01/10/2004','01/11/2004','01/12/2004','01/01/2005','01/02/2005','01/03/2005'], 
                   'RegionName': ['City of Dundee', 'City of Dundee', 'City of Dundee', 'City of Dundee', 'City of Dundee', 'City of Dundee', 'City of Dundee','City of Edinburgh', 'City of Edinburgh', 'City of Edinburgh', 'City of Edinburgh', 'City of Edinburgh', 'City of Edinburgh', 'City of Edinburgh', 'City of Edinburgh', 'City of Edinburgh', 'City of Edinburgh', 'City of Edinburgh', 'City of Edinburgh', 'City of Edinburgh', 'City of Edinburgh', 'City of Edinburgh'],
                    'SalesVolume': ['156','191','321','324','313','','','1097','811','1092','1402','1345','1526','1573','1338','1286','1317','1247','1199','940','773','897']})

print(df)
以下是我所做的:

import pandas as pd

df = pd.read_csv ('C:/Users/user/AppData/Local/Programs/Python/Python39/Scripts/uk_hpi_dataset_2021_01.csv')

df.Date = pd.to_datetime(df.Date)

sales_vol = df[df['RegionName'].str.contains('City of Edinburgh')]

sales_vol.plot(x='Date', y='SalesVolume', kind = 'bar')
plt.show()
然而,当我试着运行它时,我得到的不仅仅是12个条,而且日期也没有显示在图表上。有谁能帮我正确地完成这个问题吗


如果我正确理解您的问题,您希望为整个数据集生成爱丁堡市的月平均销售额。如果是这样,我们可以创建一个月列,并使用groupby计算月平均值。请尝试以下操作:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv ('C:/Users/user/AppData/Local/Programs/Python/Python39/Scripts/uk_hpi_dataset_2021_01.csv')

df.Date = pd.to_datetime(df.Date)
df['Month'] = pd.to_datetime(df['Date']).apply(lambda x:
                                               '{month}'.format(month=x.day).zfill(2))
sales_vol = df[df['RegionName'].str.contains('City of Edinburgh')]

sales_vol.groupby('Month').mean().plot(y='SalesVolume', kind = 'bar')
plt.show()

在本例中,我必须使用datetime格式中的“day”来提取月份,因为您的数据格式为YYYY dd mm。

我已经测试了您的代码,它似乎是我问题的答案,因此,感谢您的努力!