如何使用 Pandas Series 绘制两个不同长度/起始日期的时间序列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34401244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 00:24:52  来源:igfitidea点击:

How to use Pandas Series to plot two Time Series of different lengths/starting dates?

pythonpandasmatplotlibtime-series

提问by JianguoHisiang

I am plotting several pandas series objects of "total events per week". The data in the series events_per_weeklooks like this:

我正在绘制“每周总事件数”的几个Pandas系列对象。系列中的数据events_per_week如下所示:

Datetime
 1995-10-09     45
 1995-10-16     63
 1995-10-23     83
 1995-10-30     91
 1995-11-06    101 
Freq: W-SUN, dtype: int64

My problem is as follows. All pandas series are the same length, i.e. beginning in same year 1995. One array begins in 2003 however. events_per_week2003begins in 2003

我的问题如下。所有Pandas系列的长度都相同,即从 1995 年开始。然而,一个数组从 2003 年开始。events_per_week20032003年开始

 Datetime
     2003-09-08     25
     2003-09-15     36
     2003-09-22     74
     2003-09-29     25
     2003-09-05    193 
    Freq: W-SUN, dtype: int64

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(20,5))
ax = plt.subplot(111)
plt.plot(events_per_week)
plt.plot(events_per_week2003)

I get the following value error.

我收到以下值错误。

ValueError: setting an array element with a sequence.

How can I do this?

我怎样才能做到这一点?

回答by tglaria

I really don't get where you're having problems. I tried to recreate a piece of the dataframe, and it plotted with no problems.

我真的不明白你哪里有问题。我尝试重新创建数据框的一部分,并且绘制没有问题。

import numpy, matplotlib
data = numpy.array([45,63,83,91,101])
df1 = pd.DataFrame(data, index=pd.date_range('2005-10-09', periods=5, freq='W'), columns=['events'])
df2 = pd.DataFrame(numpy.arange(10,21,2), index=pd.date_range('2003-01-09', periods=6, freq='W'), columns=['events'])
matplotlib.pyplot.plot(df1.index, df1.events)
matplotlib.pyplot.plot(df2.index, df2.events)
matplotlib.pyplot.show()

Using Series instead of Dataframe:

使用系列而不是数据框:

ds1 = pd.Series(data, index=pd.date_range('2005-10-09', periods=5, freq='W'))
ds2 = pd.Series(numpy.arange(10,21,2), index=pd.date_range('2003-01-09', periods=6, freq='W'))
matplotlib.pyplot.plot(ds1)
matplotlib.pyplot.plot(ds2)
matplotlib.pyplot.show()