按月绘制每个产品的时间序列数据组。

问题描述 投票:0回答:1

假设使用的数据是这样的

df = pd.DataFrame({'Order_id': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
                   'Order_date': ['10/1/2020', '10/1/2020', '11/1/2020', '11/1/2020', '12/1/2020', '12/1/2020', '12/1/2020', '12/1/2020', '13/1/2020', '13/1/2020'],
                   'Product_nr': [0, 2, 1, 0, 2, 0, 2, 1, 2, 0],
                   'Quantity': [3, 1, 6, 5, 10, 1, 2, 5, 4, 3]})

#transforming the date column into datetime
df['Order_date'] = pd.to_datetime(df['Order_date'])

而我想绘制在给定的时间跨度内,每个产品每天的订购产品数量。

我最初的想法是这样的

product_groups = df.groupby(['Product_nr']) 
products_daily = pd.DataFrame()
for product, total_orders in product_groups:
    products_daily[product.day] = total_orders.values
products_daily.plot(subplots=True, legend=False)
pyplot.show()

我知道一定有 groupby('Product_nr') 和日期应该被分割成天数,用 Grouper(freq='D'). 他们也应该是一个for循环来组合他们,然后策划他们所有的,但我真的不知道如何把这些碎片在一起。我如何才能实现这个目标?我的最终目标实际上是为了绘制他们每个月每个产品超过4年的销售记录,但鉴于这里的示例数据,我把它改为每日。

也欢迎任何建议或链接的指南、教程。非常感谢!!!!!。

python pandas matplotlib data-visualization data-science
1个回答
0
投票

你可以对表进行数据透视,并使用pandas'。plot 功能。

(df.groupby(['Order_date', 'Product_nr'])
   ['Quantity'].sum()
   .unstack('Product_nr')
   .plot(subplots=True, layout=(1,3)) # change layout to fit your data
)

输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.