You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按日期分组绘制DataFrame中每日总quantity的柱状/折线图?

解决方案

要实现按日期汇总quantity并绘制柱状图/折线图,核心是先对日期维度的时间戳进行聚合求和,再可视化。以下是两种可行方法:

方法1:提取日期后分组求和

适合需要保留原DataFrame结构,或后续还要用其他时间字段的场景:

# 从Timestamp中提取日期部分(去掉时分秒)
quantities['date'] = quantities['created'].dt.date

# 按日期分组,计算当日总quantity
daily_quantity = quantities.groupby('date')['quantity'].sum()

# 绘制柱状图
daily_quantity.plot(kind='bar', title='每日总Quantity')

# 若要折线图,替换kind参数即可
daily_quantity.plot(kind='line', title='每日总Quantity趋势')

方法2:用resample按天重采样

适合已将时间列设为索引的场景,代码更简洁:

# 将created设为DataFrame的索引(确保是datetime类型)
quantities = quantities.set_index('created')

# 按天('D')重采样,求和quantity
daily_quantity = quantities['quantity'].resample('D').sum()

# 可视化(柱状图/折线图二选一)
daily_quantity.plot(kind='bar')
# daily_quantity.plot(kind='line')

为什么之前的直方图不符合预期?

你直接将created设为索引后绘制直方图,是把每个带时分秒的时间戳作为独立的X轴项,而不是按日期合并汇总,导致X轴过于密集,无法体现每日总量的趋势。通过上述聚合步骤,才能得到按日期分组的统计结果,再绘制的图表才符合需求。

内容的提问来源于stack exchange,提问作者Irina Rapoport

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 11:26:11