2

我正在加载一个数据文件,提取某些列,并使用 matplotlib 将它们绘制为 PDF。

当我将数据文件加载到 Pandas 中时,我得到一个 DateTimeIndex。如果我以这种形式绘制数据,一切顺利。

当我根据时间选择数据子集时出现问题,即:

data = data.ix[data.index >= start_time]
data = data.ix[data.index <= end_time]

现在,当我去绘制数据时,pandas 似乎发生了一些变化,因为 DateTimeIndex 是一个 npdatetime64 类型的数组,matplotlib 显然不支持这些类型并引发错误。(datetime.fromordinal 中的内容)

我怎样才能解决这个问题?

我试过绘图:

data.index.value.astype(datetime)

但这仍然会在 matplotlib 中引发错误!(Python int 不能转换为 C long)

有没有办法可以防止熊猫在我修复数据时首先破坏数据?

我正在使用 Python 2.7、Numpy 1.7、pandas 0.11、matplotlib 1.2.1。

编辑:似乎我遇到了与此处看到的相同的问题: Plot numpy datetime64 with matplotlib

4

1 回答 1

5

我在这里的 IPython 笔记本中创建了一个最小的工作示例。

诀窍是使用df.ix如下:

df_new=df.ix[start_time:end_time]

作为参考,我在这里发布了笔记本中的部分答案:


df

<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 1668 entries, 
2013-10-12 07:50:00 to 2013-10-23 21:40:00
Freq: 10T
Data columns (total 2 columns):
column_1    1668  non-null values
column_2    1668  non-null values    
dtypes: float64(2)

如您所见,df定义为从 2013 年 10 月 12 日 7:50 到 2013 年 10 月 23 日 21:40。以下是df.


df.plot()

在此处输入图像描述


现在,我们选择从 10 月 14 日 9:30 到 10 月 16 日 9:30 的数据。

df2=df.ix['2013-10-14 09:30':'2013-10-16 09:30']

df2.plot()

在此处输入图像描述


您可能会看到如何.ix用于选择间隔。您还可以执行以下相同的操作:

df['2013-10-14 09:30':'2013-10-16 09:30'].plot()

这给出了与以前相同的结果。

有关更多详细信息,您可以参考 Chang She 的演讲以及随附的关于 Time Series with Pandas的 IPython笔记本。韦斯的以下两次谈话也应该很有帮助

  1. 使用 Pandas 进行时间序列数据分析
  2. 使用 Pandas 进行时间序列操作
于 2013-10-12T08:11:26.793 回答