3 回答

TA貢獻1846條經驗 獲得超7個贊
方法#1:單行,用于窗口化最大值,使用 np.最大值。. -
In [118]: np.maximum.reduceat(listA,np.arange(0,len(listA),3))
Out[118]: array([5, 9, 8, 9])
變得更緊湊np.r_ -
np.maximum.reduceat(listA,np.r_[:len(listA):3])
方法#2:通用的 ufunc 方式
這是一個用于通用 ufunc 的函數,該窗口長度作為參數 -
def windowed_ufunc(a, ufunc, W):
a = np.asarray(a)
n = len(a)
L = W*(n//W)
out = ufunc(a[:L].reshape(-1,W),axis=1)
if n>L:
out = np.hstack((out, ufunc(a[L:])))
return out
示例運行 -
In [81]: a = [3,2,5,9,4,6,3,8,7,9]
In [82]: windowed_ufunc(a, ufunc=np.max, W=3)
Out[82]: array([5, 9, 8, 9])
在其他問題上 -
In [83]: windowed_ufunc(a, ufunc=np.min, W=3)
Out[83]: array([2, 4, 3, 9])
In [84]: windowed_ufunc(a, ufunc=np.sum, W=3)
Out[84]: array([10, 19, 18, 9])
In [85]: windowed_ufunc(a, ufunc=np.mean, W=3)
Out[85]: array([3.33333333, 6.33333333, 6. , 9. ])
標桿
對陣列數據的 NumPy 解決方案進行計時,樣本數據按以下方式縱向擴展10000x -
In [159]: a = [3,2,5,9,4,6,3,8,7,9]
In [160]: a = np.tile(a, 10000)
# @yatu's soln
In [162]: %timeit moving_maxima(a, w=3)
435 μs ± 8.54 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
# From this post - app#1
In [167]: %timeit np.maximum.reduceat(a,np.arange(0,len(a),3))
353 μs ± 2.55 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
# From this post - app#2
In [165]: %timeit windowed_ufunc(a, ufunc=np.max, W=3)
379 μs ± 6.44 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

TA貢獻1828條經驗 獲得超4個贊
使用 numpy,您可以使用零擴展列表,使其長度可被窗口大小整除,并沿第二個軸重新調整和計算:max
def moving_maxima(a, w):
mod = len(a)%w
d = w if mod else mod
x = np.r_[a, [0]*(d-mod)]
return x.reshape(-1,w).max(1)
一些例子:
moving_maxima(listA,2)
# array([3., 9., 6., 8., 9.])
moving_maxima(listA,3)
#array([5, 9, 8, 9])
moving_maxima(listA,4)
#array([9, 8, 9])

TA貢獻1963條經驗 獲得超6個贊
如果你想要一個單行,你可以使用列表理解:
listA = [3,2,5,9,4,6,3,8,7,9]
listB=[max(listA[i:i+3]) for i in range(0,len(listA),3)]
print (listB)
它返回:
[5, 9, 8, 9]
當然,代碼可以更動態地編寫:如果你想要不同的窗口大小,只需更改為任何整數。3
添加回答
舉報