Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

python - Converting pandas DatetimeIndex to 'float days format' with Matplotlib.dates.datestr2num

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]

But is there a better way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...