piRSquared piRSquared - 1 month ago 5
Python Question

quickest way to look up nearest index value

consider the time series

s
and it's index
tidx


tidx = pd.date_range('2010-12-31', periods=3, freq='M')
s = pd.Series([0, 31, 59], tidx)


If I wanted to use
s
as a lookup series and passed the date
'2011-02-23'
, I'd want to get the most recently available value. In this case that would be
31
.

I've done

s.resample('D').ffill().loc['2011-02-23']

31


This does the job, but I had to resample the whole series just to get a single value. What is a more appropriate way to do this?

Answer

You could use searchsorted -

s[s.index.searchsorted('2011-02-23','right')-1]
Comments