Pandas DataFrame - 使用 ols/线性回归时,“无法将日期时间类型从 [datetime64[ns]] 转换为 [float64]”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40453744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas DataFrame - 'cannot astype a datetimelike from [datetime64[ns]] to [float64]' when using ols/linear regression
提问by Cole Starbuck
I have a DataFrame as follows:
我有一个 DataFrame 如下:
Ticker Date Close
0 ADBE 2016-02-16 78.88
1 ADBE 2016-02-17 81.85
2 ADBE 2016-02-18 80.53
3 ADBE 2016-02-19 80.87
4 ADBE 2016-02-22 83.80
5 ADBE 2016-02-23 83.07
...and so on. The Date
column is the issue. I'm trying to get the linear regression of the Date
column with the Close
column:
...等等。该Date
列是问题。我正在尝试Date
使用该Close
列获得该列的线性回归:
ols1 = pd.ols(y=ADBE['Close'], x=ADBE['Date'], intercept=True)
I get the following error:
我收到以下错误:
TypeError: cannot astype a datetimelike from [datetime64[ns]] to [float64]
I've tried multiple ways of getting rid of this error, for examples:
我尝试了多种方法来消除此错误,例如:
dates_input = ADBE['Date'].values.astype('datetime64[D]')
dates_input = ADBE['Date'].values.astype('float')
The second dates_input
attempt returns the type as pandas.core.series.Series
but I still get an error message.
第二次dates_input
尝试返回类型 aspandas.core.series.Series
但我仍然收到错误消息。
Does anyone know how to get the Date
column to work and get rid of this TypeError?
有谁知道如何让Date
列工作并摆脱这个 TypeError?
回答by jezrael
You need:
你需要:
ADBE['Date'] = ADBE['Date'].values.astype(float)
and then:
进而:
ols1 = pd.ols(y=ADBE['Close'], x=ADBE['Date'], intercept=True)