使用 Matplotlib.dates.datestr2num 将 Pandas DatetimeIndex 转换为“浮动天数格式”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27993540/
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
Converting pandas DatetimeIndex to 'float days format' with Matplotlib.dates.datestr2num
提问by birone
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:
一些 Matplotlib 方法需要'float days format' 天数。datestr2num 是用于此的转换器函数,但它会与相关的Pandas对象发生冲突:
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]
But is there a better way?
但是有更好的方法吗?
回答by joris
You can use the to_pydatetimemethod of the DatetimeIndex (this will convert it to an array of datetime.datetime's, and mpl.dates.date2numwill know how to handle those):
您可以使用to_pydatetimeDatetimeIndex的方法(这会将其转换为datetime.datetime's的数组,并mpl.dates.date2num知道如何处理这些):
mpl.dates.date2num(df.index.to_pydatetime())
The reason that date2numdoes 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).
date2num不本地处理 Pandas DatetimeIndex的原因是因为 matplotlib 尚不支持 numpy datetime64 dtype(这是数据存储在 DatetimeIndex 中的方式)。

