Home > Software design >  Using polyfit with date series
Using polyfit with date series

Time:06-02

How can I manage the date series with this kind of data into the polyfit without any errors.

data1 = np.array(['1801-01-01', '1802-01-01', '1803-01-01', '1804-01-01', '1805-01-01'])
data2 = np.array([5, 6, 7, 8, 9])
ser1 = pd.Series(data1)
ser2 = pd.Series(data2)
date = pd.to_datetime(ser1)
a, b = np.polyfit(date, ser2, 1)

the error message says

UFuncTypeError: ufunc 'add' cannot use operands with types dtype('<M8[ns]') and dtype('float64')

Is there a way to transform the date into a float to make the polyfit work?

CodePudding user response:

Convert datetimes to unix times by casting to int64:

a, b = np.polyfit(date.astype(np.int64), ser2, 1)
print (a, b)
3.169241676570259e-17 174.020212777763
  • Related