Max in a sliding window in NumPy array

后端 未结 5 1212
囚心锁ツ
囚心锁ツ 2020-11-30 10:13

I want to create an array which holds all the max()es of a window moving through a given numpy array. I\'m sorry if this sounds confusing. I\'ll give an examp

5条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 11:02

    If you have two dimension data, for example stock price and want to get rolling max or whatever, this will works. Caculating without using iteration.

    n = 5  # size of rolling window
    
    data_expanded = np.expand_dims(data, 1)
    data_shift = [np.roll(data_expanded, shift=-i, axis=2) for i in range(n)]
    data_shift = np.concatenate(data_shift, axis=1)
    
    data_max = np.max(data_shift, axis=1)  # max, mean, std...
    

提交回复
热议问题