20

I have a DataFrame as follows:

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:

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.

Does anyone know how to get the Date column to work and get rid of this TypeError?

Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219
Cole Starbuck
  • 603
  • 3
  • 11
  • 21

1 Answers1

17

You need:

ADBE['Date'] = ADBE['Date'].values.astype(float)

and then:

ols1 = pd.ols(y=ADBE['Close'], x=ADBE['Date'], intercept=True)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • 1
    I made a mistake; for others who might make the same mistake; be careful not to use `Series.astype(float)` (as in; `pd.Series(ADBE['Date'].values).astype(float)`; notice @jezrael's answer uses `ndarray.astype(float)` (directly on the `.values.astype(float)`) – Nate Anderson Mar 24 '20 at 01:58
  • I was getting the error TypeError: cannot astype a datetimelike from [datetime64[ns]] to [int32] when trying to run the line df_['Date']=(df['Date'].astype(int)// 10**9).astype('U10') Changing above line to df['Date']=(df['Date'].values.astype(int)// 10**9).astype('U10') solved by issue. – kraftwerk Oct 27 '22 at 17:05