Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

interp1d for pandas time series

Tags:

pandas

scipy

I want to interpolate between times in a pandas time series. I would like to use scipy.interpolate.interp1d (or similar). The pandas.interpolate function is undesirable, as it would require inserting nan values and then replace them using interpolation (and thus modifying the dataset). What I tried to do:

from datetime import datetime
import scipy.interpolate as si
import pandas as pd
d1 = datetime(2019, 1, 1)
d2 = datetime(2019, 1, 5)
d3 = datetime(2019, 1, 10)
df = pd.DataFrame([1, 4, 2], index=[d1, d2, d3], columns=['conc'])
import scipy.interpolate as si
f = si.interp1d(df.index, df.conc)
f(datetime(2019, 1, 3))

All is good until the last line, where I get an ValueError: object arrays are not supported. Strangely enough f.x nicely shows the dates as dtype='datetime64[ns], so I was hoping it would work. Anybody know how to get this to work?

like image 810
Mark Bakker Avatar asked Dec 11 '25 15:12

Mark Bakker


1 Answers

This works, but is arguably a bit ugly:

f = si.interp1d(pd.to_numeric(df.index), df.conc)
f(pd.to_numeric(pd.to_datetime(['2019-1-3'])))
like image 91
Mark Bakker Avatar answered Dec 13 '25 04:12

Mark Bakker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!