使用Matplotlib.dates.datestr2num将 pandas DatetimeIndex转换为'float days format' [英] Converting pandas DatetimeIndex to 'float days format' with Matplotlib.dates.datestr2num

查看:439
本文介绍了使用Matplotlib.dates.datestr2num将 pandas DatetimeIndex转换为'float days format'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

某些Matplotlib方法需要使用浮动日格式" 的日期. datestr2num是为此的转换器函数,但会被相关的pandas对象所取代:

Some Matplotlib methods need days in 'float days format'. datestr2num is a converter function for this, but it falls over with the relevant pandas objects:

In [3]: type(df.index)
Out[3]: pandas.tseries.index.DatetimeIndex
In [4]: type(df.index[0])
Out[4]: pandas.tslib.Timestamp
In [5]: mpl.dates.date2num(df.index)
Out [5]: ...
AttributeError: 'numpy.datetime64' object has no attribute 'toordinal'

这以浮动日格式"提供了可用的时间列表:

This provides a usable list of times in 'float days format':

dates = [mpl.dates.date2num(t) for t in df.index]

但是有更好的方法吗?

推荐答案

您可以使用DatetimeIndex的to_pydatetime方法(这会将其转换为datetime.datetime的数组,而mpl.dates.date2num将知道如何处理这些):

You can use the to_pydatetime method of the DatetimeIndex (this will convert it to an array of datetime.datetime's, and mpl.dates.date2num will know how to handle those):

mpl.dates.date2num(df.index.to_pydatetime())

date2num不能本地处理pandas DatetimeIndex的原因是因为matplotlib还不支持numpy datetime64 dtype(这是将数据存储在DatetimeIndex中的方式).

The reason that date2num does not natively handle a pandas DatetimeIndex, is because matplotlib does not yet support the numpy datetime64 dtype (which is how the data are stored in a DatetimeIndex).

这篇关于使用Matplotlib.dates.datestr2num将 pandas DatetimeIndex转换为'float days format'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆