AttributeError: 'numpy.datetime64' object has no attribute 'toordinal'

巧了我就是萌 提交于 2019-12-20 03:32:31

问题


I'm trying to draw a timeline

import datetime          as da
import matplotlib.dates  as dt

# Data
df = pd.DataFrame({'A': [da.datetime(2017,1,5,9,8),   da.datetime(2017,1,5,9,9),  da.datetime(2017,1,7,9,19), da.datetime(2017,1,7,9,19),  da.datetime(2017,1,7,9,19), da.datetime(2017,2,7,9,19), da.datetime(2017,2,7,9,19)],
                   'B': [da.datetime(2017,1,5,9,9),   da.datetime(2017,1,5,9,12), da.datetime(2017,1,7,9,26), da.datetime(2017,1,7,9,20),  da.datetime(2017,1,7,9,21), da.datetime(2017,2,7,9,23), da.datetime(2017,2,7,9,25)],
                   'C' :[1,                           2,                          3,                          4,                           5,                          6,                          7 ]})

# Visualisation
ax = plt.subplot()
ax = plt.hlines(df.C,
    dt.date2num(df.A),
    dt.date2num(df.B))

but getting the error:

AttributeError: 'numpy.datetime64' object has no attribute 'toordinal'

I think it's caused by the data type:

df.A.dtype 
dtype('<M8[ns]')

I tried some recommended solutions (converter & pandacnv) but I still couldn't get it to work.


回答1:


If your aim is to plot horizontal lines using the A and B columns as x-axis and C column as y-axis, you can directly use arrays of dataframe. Added 1 day to B column since the time changes very minimal to observe that in graph:

df['B'] = df['B']+pd.Timedelta("1D")
ax = plt.subplot()
ax.hlines(df.C.values, df.A.values, df.B.values, lw=2)
plt.show()

Output Plot:




回答2:


I did not see any problem with the data type. The issue might be the date in column B. as an alternative to @Sandeep Kadapa, you can just set the max date, as xmax. For example:

 ax = plt.subplot()
ax.hlines(df.C.values, df.A.values, xmax='2017-01-02')
plt.show()


来源:https://stackoverflow.com/questions/51101252/attributeerror-numpy-datetime64-object-has-no-attribute-toordinal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!