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

时间:2021-06-02 20:08:58

标签: python pandas jupyter-notebook

论文中的问题:“通过条形图 - 显示每年平均最繁忙的月份 爱丁堡市的销售量,条形图应该有 12 个条形, 每个月一个,总数应该是那个的平均销售额 每月的可用数据。”

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

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 条,而且图表上也未显示日期。谁能帮我正确完成这个问题?

Here is an image of the output I've got

1 个答案:

答案 0 :(得分:0)

如果我正确理解您的问题,您希望为爱丁堡市的整个数据集生成每月平均销售量。如果是这样,想法是创建一个月份列并使用 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()

在此示例中,我必须使用日期时间格式中的“day”来提取月份,因为您的数据格式为 YYYY-dd-mm。