I'm trying to use pandas.Index.get_loc to return the index (as an int
) of the nearest value, but occasionally it returns a slice
object instead. According to the documentation,
get_loc returns int if unique index, slice if monotonic index, else mask.
But it doesn't look like the behavior is consistent. For example, with the following index:
idx = pd.DatetimeIndex(['2019-12-24 12:04:54',
'2019-12-26 20:09:22',
'2020-12-27 07:44:35'])
Using idx.get_loc('2019-12-27', method='ffill')
returns slice(2, 2, None)
, whereas idx.get_loc('2019-12-29', method='ffill')
returns 2
. Changing the method from 'ffill'
to 'bfill'
doesn't seem to change the result.
My aim is to slice all points from the beginning of the index like idx[:i]
where i
is an int returned by get_loc
. Another solution might to modify the beginning of the slice
object, if that is possible.
Edit:
Apparently, a slice
is a built-in object with read-only data attributes start, stop and step (see docs here). This means you can check whether the result of get_loc
is an int
and if not, use idx[:slice.stop]
to get all elements up to the desired index.
I'm still interested in the original question though.