problems in “pandas datetime convert to num”

匿名 (未验证) 提交于 2019-12-03 07:50:05

问题:

I use pandas to read a csv file to do some analysis. But the returned type is pandas.core.series.Series, which can not be converted to num using the command matplotlib.dates.date2num. Below is my code:

import pandas as pd import numpy as np from bokeh.plotting import figure, output_file, show import matplotlib.dates as mdates import time import matplotlib.pyplot as plt  AAPL = pd.read_csv(     "http://ichart.yahoo.com/table.csvs=AAPL&a=0&b=1&c=2009&d=0&e=1&f=2010",     parse_dates=['Date'] )  x = AAPL['Date'] y = AAPL['Close'] print type(x) x = mdates.date2num(x)  z4 = np.polyfit(x, y, 6) p4 = np.poly1d(z4) xx = np.linspace(x.min(), x.max(), 100) dd = mdates.num2date(xx) plt.plot(dd,p4(xx)) 

The command print type(x) returns pandas.core.series.Series. This one x = mdates.date2num(x) returns the error as: AttributeError: 'numpy.datetime64' object has no attribute 'toordinal'.

Any one can shed a light on me for this issue?

回答1:

Use x.astype(datetime) to convert to datetime.

from datetime import datetime x = mdates.date2num(x.astype(datetime))  z4 = np.polyfit(x, y, 6) p4 = np.poly1d(z4) xx = np.linspace(x.min(), x.max(), 100) dd = mdates.num2date(xx) plt.plot(dd,p4(xx)) 


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