【问题标题】:How to use Pandas Series to plot two Time Series of different lengths/starting dates?如何使用 Pandas Series 绘制两个不同长度/开始日期的时间序列?
【发布时间】:2016-03-27 20:32:32
【问题描述】:

我正在绘制“每周总事件”的几个熊猫系列对象。系列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

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

 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)

我收到以下值错误。

ValueError: setting an array element with a sequence.

我该怎么做?

【问题讨论】:

  • 您可以将每一列提取到一个变量中,然后绘制(x,y)。您的代码中的events_per_week 是什么?一个系列?
  • @tglaria 'events_per_week' 是一个始于 1995 年的系列。
  • @tglaria 我不明白这个“你可以将每一列提取到一个变量中,然后绘制(x,y)”
  • 我的意思是将第 1 列存储为日期数组,将第 2 列存储为浮点数组,然后将plot(column 1, column 2) 存储,尽管我确信有一种直接的绘制方法。
  • 好的,您可以使用events_per_week.plot('Datetime', 'name_of_other_column')plt.show() 进行绘图

标签: python pandas matplotlib time-series


【解决方案1】:

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

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()

使用系列而不是数据框:

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()

【讨论】:

  • 问题是系列event_per_weeks 是一个比event_per_weeks2003 长得多的数组。所以,必须有某种方法来绘制两者。
  • 见上文。 event_per_weeks 是 1100 周的时间序列,从 1995 年至今。 event_per_weeks2003 是一个大约 500 周的时间序列。同时绘制两者时会出现 ValueError。
  • 您的原始文件可能有错误?可以上传吗?我正在绘制两个数据框,没问题。
  • 这可能是我的问题。我使用的是熊猫系列,而不是数据框。
  • 我用数据系列尝试了同样的事情,我没有收到任何错误(虽然我没有横轴日期)。
猜你喜欢
  • 2016-07-31
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-28
  • 2016-06-23
  • 2018-05-08
  • 1970-01-01
相关资源
最近更新 更多