AttributeError: 'numpy.datetime64' object

2019-02-25 21:36发布

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.

2条回答
一夜七次
2楼-- · 2019-02-25 22:02

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:

enter image description here

查看更多
淡お忘
3楼-- · 2019-02-25 22:11

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()
查看更多
登录 后发表回答