how do I calculate a rolling idxmax

前端 未结 5 1745
梦如初夏
梦如初夏 2020-11-30 12:16

consider the pd.Series s

import pandas as pd
import numpy as np

np.random.seed([3,1415])
s = pd.Series(np.random.randint(0, 10, 10         


        
5条回答
  •  猫巷女王i
    2020-11-30 12:34

    You can also simulate the rolling window by creating a DataFrame and use idxmax as follows:

    window_values = pd.DataFrame({0: s, 1: s.shift(), 2: s.shift(2)})
    s.index[np.arange(len(s)) - window_values.idxmax(1)]
    
    Index(['a', 'b', 'c', 'c', 'e', 'e', 'e', 'f', 'i', 'i'], dtype='object', name=0)
    

    As you can see, the first two terms are the idxmax as applied to the initial windows of lengths 1 and 2 rather than null values. It's not as efficient as the accepted answer and probably not a good idea for large windows but just another perspective.

提交回复
热议问题