working4coins
working4coins

Reputation: 2027

Interpolate only one value of a TimeSerie using Python / Pandas

I have a pandas.core.series.TimeSeries named ts like this:

timestamp
2013-08-11 14:23:50        0.3219
2013-08-11 14:23:49        0.3222
2013-08-11 14:19:14        0.3305
2013-08-11 00:47:15        0.3400
2013-08-11 00:47:15.001    0.3310
2013-08-11 00:47:15.002    0.3310
2013-08-10 22:38:15.003    0.3400
2013-08-10 22:38:14        0.3403
2013-08-10 22:38:13        0.3410

Index of this TimeSerie are irregularly spaced.

I would like to have value of ts for a given datetime such as 2013-08-11 14:20:00

I just need to interpolate ONE value, not the whole TimeSerie

I just want to interpolate data using a linear function between the previous index (2013-08-11 14:23:49) and the next index (2013-08-11 14:19:14)

Upvotes: 5

Views: 2566

Answers (2)

Jim O
Jim O

Reputation: 136

Thank-you Dan Allan. I'm afraid I don't have the reputation to comment but Dan Allan's interpolate function raises an exception if asked to interpolate a time already defined in the ts index. E.g.

s = pd.to_datetime('2015-08-26 00:00:00')
e = pd.to_datetime('2015-08-26 00:10:00')
ts=pd.Series([0,8000],index=[s,e])
interpolate(ts,pd.to_datetime('2015-08-26 00:00:00'))

My minor modification of the above is:

def interpolate(ts, target):
    if target in ts.index:
        return ts[target]
    ts1 = ts.sort_index()
    b = (ts1.index > target).argmax() # index of first entry after target
    s = ts1.iloc[b-1:b+1]
    # Insert empty value at target time.
    s = s.reindex(pd.to_datetime(list(s.index.values) + [pd.to_datetime(target)]))
    return s.interpolate(method='time').loc[target]

Upvotes: 8

Dan Allan
Dan Allan

Reputation: 35235

Take a subset of the Series including only the entry above and below your target. Then use interpolate.

def interpolate(ts, target):
    ts1 = ts.sort_index()
    b = (ts1.index > target).argmax() # index of first entry after target
    s = ts1.iloc[b-1:b+1]
    # Insert empty value at target time.
    s = s.reindex(pd.to_datetime(list(s.index.values) + [pd.to_datetime(target)]))
    return s.interpolate('time').loc[target]

Example:

interpolate(ts, '2013-08-11 14:20:00')
2013-08-11 14:20:00    0.329112

Upvotes: 6

Related Questions