python - 具有不同时间索引的 Pandas 系列

标签 python pandas

我有以下代码

 ser = pandas.Series(range(5),index=pandas.date_range('20130722','20130726',freq='D'))
ser1 = pandas.Series( range(4,9), index = ser.index + datetime.timedelta(days=3))

当我一个接一个地绘制它们时(ser.plot(),然后是 ser1.plot()),我得到了正确的图片。

现在修改ser1的定义如下

ser1 = pandas.Series( range(4,9), index = ser.index + datetime.timedelta(days=3.1))

并重复这两个绘图命令(与上面的顺序相同)。我得到的图片仅显示 ser1,x 轴显示“3982 年 7 月 27 日”。如果您先执行 ser1.plot(),然后执行 ser.plot(),您也会得到一张不正确的图片,但与第一个不正确的图片略有不同。 (我会发照片,但是没有足够的声望点...)

为什么会这样?

最佳答案

我已将 matplotlib.pyplot 导入为 plt

这让他们在同一个数字上,我认为这就是你想要的。我基本上将 ser1 重新采样到 ser 的较低频率时间戳。您可以使用 In [33]: ser1.resample('D', how='mean') 明确地执行此操作,但在这种情况下这并不重要,因为每天只有一次观察.重要的是,如果您试图将它们放在同一个图上,它们共享相同的 x 轴单位。

In [25]: fig = plt.figure()

In [26]: ax = fig.add_subplot(111)

In [27]: ax.plot(ser.index.date, ser)
Out[27]: [<matplotlib.lines.Line2D at 0x10616e150>]

In [28]: ax.plot(ser1.index.date, ser1)
Out[28]: [<matplotlib.lines.Line2D at 0x107981050>]

In [29]: plt.draw()

enter image description here

如果你想完全避免 matplotlit,首先加入这两个系列并在生成的 DatFrame 上调用 plot:

In [37]: pd.concat([ser, ser1.resample('D', how='mean')], axis=1).plot()
Out[37]: <matplotlib.axes.AxesSubplot at 0x1064aa190>

默认情况下,这会更好地处理刻度标签:

enter image description here

关于python - 具有不同时间索引的 Pandas 系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17884693/

相关文章:

python - 可以使用 while(file >> ...) C++ 习惯用法来读取 Cython 中的文件吗?

python - Gensim Doc2Vec - 将语料库句子传递给 Doc2Vec 函数

python - 过滤包含特定值的多个列

python - Pandas 数据框 to_html : Highlighting table rows

python - 仅计算 Pandas 数据系列中的当前行和前一行

python - OWL2、SWRL : Query if item is in range of another item?

python - python tkinter 递归中的皮亚诺曲线

python - 如何在模板中呈现 Django 表单字段

python - Series.index 与 Series.index.values

python - 如何应用一个使用两个系列作为输入的函数,输出是每个参数组合的函数结果的数据帧?