我正在尝试使用pandas.Index.get_loc返回最接近值的索引(作为int
),但偶尔它返回一个slice
对象。根据文档,
get_loc如果唯一索引返回int,如果单调索引则返回slice,否则返回mask。
但是看起来行为并不始终如一。例如,具有以下索引:
idx = pd.DatetimeIndex(['2019-12-24 12:04:54',
'2019-12-26 20:09:22',
'2020-12-27 07:44:35'])
使用idx.get_loc('2019-12-27', method='ffill')
返回slice(2, 2, None)
。而idx.get_loc('2019-12-29', method='ffill')
返回2
。
我的目标是从索引的开头像idx[:i]
一样切出所有点,其中i
是get_loc
返回的int。如果可能的话,另一种解决方案可能是修改slice
对象的开头。
编辑:显然,slice
是带有read-only数据属性开始,停止和步进的内置对象(请参阅docs here)。这意味着您可以检查get_loc
的结果是否为int
,如果不是,请使用idx[:slice.stop]
使所有元素均达到所需的索引。
尽管我仍然对原始问题感兴趣。
我相信单调只是意味着您具有一系列相同的索引。因此,如果索引是按顺序排列的,那么您唯一需要的信息就是第一个位置,然后是要操作的最后一个位置。
另一方面,如果它们不是单调的,则意味着它们不是按顺序排列的,那么您需要列出所有位置的列表才能进行操作。
例如:
import pandas as pd
monotonic = pd.DatetimeIndex(['2019-12-24 12:04:54',
'2019-12-24 12:04:54',
'2019-12-24 12:04:54',
'2019-12-26 20:09:22',
'2020-12-27 07:44:35'])
print(f'this is monotonic so I return a slice {idx.get_loc("2019-12-24 12:04:54")}')
non_monotonic = pd.DatetimeIndex(['2019-12-24 12:04:54',
'2019-12-24 12:04:54',
'2019-12-24 12:04:54',
'2019-12-26 20:09:22',
'2019-12-24 12:04:54',
'2020-12-27 07:44:35'])
print(f'this is not monotonic so I need to return a list with all locs {idx.get_loc("2019-12-24 12:04:54")}')
输出:
this is monotonic so I return a slice slice(0, 3, None)
this is not monotonic so I need to return a list with all locs: [0 1 2 4]