Python Pandas - 年度数据的每周折线图

标签 python pandas visualization

我有一个以 30 分钟为间隔的能源消耗读数的年度数据集:

                      data
2012-11-01 00:00:00  0.177
2012-11-01 00:30:00  0.141
2012-11-01 01:00:00  0.112
2012-11-01 01:30:00  0.082
2012-11-01 02:00:00  0.080
...

如何绘制显示每周数据消耗的多线图?也就是说,最终我会得到一个包含 52 条线的图表,其中 x 轴是一周中的时间(天?半天?小时?),y 轴是消耗量。

谢谢

最佳答案

考虑索引为 tidx 的数据帧 df

tidx = pd.date_range('2016-01-01', '2017-01-01', freq='30T')
df = pd.DataFrame(dict(data=(np.random.randn(len(tidx)) + .01).cumsum()), tidx)

创建相对于第一个日期的时间增量

deltas = df.index - df.index[0]

根据增量创建周数

week = deltas.days // 7

使用 pd.MultiIndex 构建新的 pd.Series 对象

d1 = pd.Series(
    df.data.values,
    [deltas - pd.to_timedelta(week, 'w'), week]
)

展开

# d2 = d1.unstack().add_prefix('Week ') # working version

# explanation version
d2 = print(d1.unstack().add_prefix('Week '))
d2.iloc[:10, :5]

            Week 0    Week 1     Week 2    Week 3     Week 4
00:00:00 -0.973634 -5.350765   6.918354 -3.536488  22.489763
00:30:00 -2.320088 -5.632370   6.670572 -4.852697  24.493568
01:00:00 -2.499885 -3.458980   8.748229 -4.059241  25.278759
01:30:00 -3.525366 -2.286180   8.345489 -5.241154  26.086324
02:00:00 -2.110594 -2.801211   8.626546 -6.840205  28.028737
02:30:00 -2.811840 -2.605900   9.224140 -6.601106  28.014257
03:00:00 -4.119560 -3.497173   9.801411 -6.431539  29.284452
03:30:00 -4.927063 -3.406615  11.729483 -5.526467  27.834364
04:00:00 -5.573758 -2.559643  13.653698 -3.948048  28.956422
04:30:00 -4.878375 -4.322923  12.017081 -2.862244  28.364504

齐心协力

tidx = pd.date_range('2016-01-01', '2017-01-01', freq='30T')
df = pd.DataFrame(dict(data=(np.random.randn(len(tidx)) + .01).cumsum()), tidx)

deltas = df.index - df.index[0]

week = deltas.days // 7

d1 = pd.Series(
    df.data.values,
    [deltas - pd.to_timedelta(week, 'w'), week]
)

d2 = d1.unstack().add_prefix('Week ')

ax = d2.plot(rot=30, colormap='jet')
lg = ax.legend(ncol=4, loc=2, bbox_to_anchor=(1.05, 1))

enter image description here

关于Python Pandas - 年度数据的每周折线图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44272637/

相关文章:

Python请求图片上传HTTP POST

python - pyximport 与 cgal 构建错误 : undefined symbol "__gmpq_equal"

python - Pandas ._libs.hashtable.PyObjectHashTable.get_item KeyError : 0

visualization - Neo4j 浏览器 : Display relationship property as edge label not working

类似于 MATLAB 的 Haskell 绘图库

python - 在新进程中执行 python 代码比在主进程中慢得多

refactoring - 更多pythonic迭代方式

python - 迭代 df 行并附加到不带名称和 dtype 的列表

python - 无法使用钟摆来解析系列中的日期,但可以一一解析

具有均值和标准差的 R 手动箱线图 (ggplot2)