Max in a sliding window in NumPy array

后端 未结 5 1209
囚心锁ツ
囚心锁ツ 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:07

    Pandas has a rolling method for both Series and DataFrames, and that could be of use here:

    import pandas as pd
    
    lst = [6,4,8,7,1,4,3,5,7,8,4,6,2,1,3,5,6,3,4,7,1,9,4,3,2]
    lst1 = pd.Series(lst).rolling(5).max().dropna().tolist()
    
    # [8.0, 8.0, 8.0, 7.0, 7.0, 8.0, 8.0, 8.0, 8.0, 8.0, 6.0, 6.0, 6.0, 6.0, 6.0, 7.0, 7.0, 9.0, 9.0, 9.0, 9.0]
    

    For consistency, you can coerce each element of lst1 to int:

    [int(x) for x in lst1]
    
    # [8, 8, 8, 7, 7, 8, 8, 8, 8, 8, 6, 6, 6, 6, 6, 7, 7, 9, 9, 9, 9]
    

提交回复
热议问题