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?
DataFrame.astype() method is used to cast a pandas object to a specified dtype. astype() function also provides the capability to convert any suitable existing column to categorical type. DataFrame.astype() function comes very handy when we want to case a particular column data type to another data type.
In order to be able to work with it, we are required to convert the dates into the datetime format. Code #1 : Convert Pandas dataframe column type from string to datetime format using pd.to_datetime() function. Output : As we can see in the output, the data type of the ‘Date’ column is object i.e. string.
The pandas library provides a DateTime object with nanosecond precision called Timestamp to work with date and time values. The Timestamp object derives from the NumPy’s datetime64 data type, making it more accurate and significantly faster than Python’s DateTime object.
DataFrame.astype () method is used to cast a pandas object to a specified dtype. astype () function also provides the capability to convert any suitable existing column to categorical type. DataFrame.astype () function comes very handy when we want to case a particular column data type to another data type.
You need:
ADBE['Date'] = ADBE['Date'].values.astype(float)
and then:
ols1 = pd.ols(y=ADBE['Close'], x=ADBE['Date'], intercept=True)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With