加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 查找最近索引值的最快方法

发布时间:2020-12-20 12:11:31 所属栏目:Python 来源:网络整理
导读:考虑时间序列s和它的索引tidx tidx = pd.date_range('2010-12-31',periods=3,freq='M')s = pd.Series([0,31,59],tidx) 如果我想使用s作为查找系列并通过日期’2011-02-23′,我想获得最近可用的值.在这种情况下,这将是31. 我弄完了 s.resample('D').ffill().l
考虑时间序列s和它的索引tidx

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

如果我想使用s作为查找系列并通过日期’2011-02-23′,我想获得最近可用的值.在这种情况下,这将是31.

我弄完了

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

31

这样做了,但我不得不对整个系列进行重新采样,以获得单个值.有什么更合适的方法呢?

解决方法

你可以使用 searchsorted

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

有趣的是你打败自己!所以,这里有更多的NumPy进一步提升性能 –

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

运行时测试 –

In [235]: tidx = pd.date_range('2010-12-31',periods=300,freq='M')
     ...: s = pd.Series(range(300),tidx)
     ...: 

In [236]: s[s.index.searchsorted('2035-03-23','right')-1]
Out[236]: 290

In [237]: s[s.index.values.searchsorted(np.datetime64('2035-03-23'),'right')-1]
Out[237]: 290

In [238]: %timeit s[s.index.searchsorted('2035-03-23','right')-1]
10000 loops,best of 3: 63 μs per loop

In [239]: %timeit s[s.index.values.searchsorted(np.datetime64('2035-03-23'),best of 3: 46.7 μs per loop

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读