【发布时间】:2013-09-22 13:42:39
【问题描述】:
我正在尝试使用 matplotlib 和 pandas 绘制一些数据。但是,当使用 DateFormatter 时,日期的渲染不正确取决于我从 DataFrame 中过滤出的内容:
下面两个示例中的日期使用 matplotlib 呈现为“2013 年 8 月 20 日 00 日”,正如预期的那样:
df['metric2'].plot()
ax = gca()
ax.xaxis.set_major_formatter(DateFormatter('%B %d %H %Y'))
draw()
df[df['metric1']>1000]['metric2'].plot()
ax = gca()
ax.xaxis.set_major_formatter(DateFormatter('%B %d %H %Y'))
draw()
但是使用下面的代码,日期被呈现为“February 01 00 1048”:
df[df['browser']=='Chrome/29']['metric2'].plot()
ax = gca()
ax.xaxis.set_major_formatter(DateFormatter('%B %d %H %Y'))
draw()
【问题讨论】:
-
如果没有看到其中一些数据,就很难诊断出问题。
-
可能相关stackoverflow.com/questions/13988111/…,因为pandas仍然在搞砸日期处理代码。
-
原始文件中的日期看起来像“2013-08-18 00”,后跟浏览器(采用上述格式)和 3 个指标。以下是我如何将文件中的数据提取到 pandas 中:
def dateParserHour(time_string): return datetime.datetime.strptime(time_string, '%Y-%m-%d %H')和pd.read_table('file.txt', index_col=0, parse_dates=True, date_parser=dateParserHour) -
您可以只显示
df.head()或其他数据子集而不是尝试描述它吗?谢谢。 -
我找到了解决办法。出于某种原因,当我绘制上面的第三个示例时,matplotlib 无法与我的 TimeSeries 配合使用。如果我用下面的代码重建索引然后绘图(使用相同的 DateFormatter() 函数,它工作正常。
df2 = df[df['browser']=='Chrome/29']['metric2']; df2.index = df2.index.astype(datetime.datetime);
标签: python matplotlib pandas