【问题标题】:quickest way to look up nearest index value查找最近索引值的最快方法
【发布时间】:2017-03-15 03:41:11
【问题描述】:

考虑时间序列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

这可以完成工作,但我不得不重新采样整个系列以获得单个值。有什么更合适的方法来做到这一点?

【问题讨论】:

    标签: python performance pandas numpy


    【解决方案1】:

    这个呢?

    In [150]: s[s.index <= '2011-02-23'].tail(1)
    Out[150]:
    2011-01-31    31
    Freq: M, dtype: int64
    

    PS 只有在对索引进行排序时才会起作用...

    【讨论】:

      【解决方案2】:

      我用s.index.get_loc()

      docs

      它允许找到“最近”的索引值位置。

      s.iloc[s.index.get_loc('2011-02-23', 'ffill')]
      

      【讨论】:

        【解决方案3】:

        你可以使用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'),'right')-1]
        10000 loops, best of 3: 46.7 µs per loop
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-07-19
          • 1970-01-01
          • 2021-10-28
          • 1970-01-01
          • 2018-06-05
          • 2022-10-25
          • 1970-01-01
          • 2016-06-09
          相关资源
          最近更新 更多