Convert pandas DatetimeIndex to "float days" format using Matplotlib.dates.datestr2num

Some Matplotlib methods need 'float days format' days . datestr2num is a converter function for this, but it crashes with the corresponding 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 gives a useful list of times in the "float days" format:

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

But is there a better way?

+6
source share
1 answer

You can use the to_pydatetime method for DatetimeIndex (this will convert it to a datetime.datetime array, and mpl.dates.date2num will know how to handle this):

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

The reason date2num does not handle the pandas DatetimeIndex object is not because matplotlib does not yet support the numpy datetime64 dtype (how data is stored in DatetimeIndex).

+8
source

Source: https://habr.com/ru/post/981131/


All Articles