Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using polyfit with date series

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading