[英]Finding (and recording) the maximum values of slices of a numpy array
給定一個numpy數組,如a = [0, 3, 2, 4, 0, 2, 3, 1, 1, 6, 2]
0,3,2,4,0,2,3,1,1,6,2 a = [0, 3, 2, 4, 0, 2, 3, 1, 1, 6, 2]
,是否有一種簡單的方法來記錄每3個值的最大值? 數組的長度可以不是3的倍數。在這種情況下,結果應該是b = [3, 4, 3, 6]
。
我想到了一些類似的東西
b = [max(a[k:k+3]) for k in range(0, len(a), 3)
但它沒有考慮3的最后一個倍數之后的值(它應該)。
我還想過重新排列numpy數組,使它有3 * n行,並使用numpy模塊沿着正確的軸取最大值,但是,我再也不知道如何在最后一個之后處理這些值3的倍數。
方法#1
我們可以使用np.ufunc.reduceat
來執行這樣的分組/ np.ufunc.reduceat
減少操作。 因此,為了在每個區間內獲得maximum
,我們將 -
W = 3 # group width
np.maximum.reduceat(a,np.r_[:len(a):W])
樣品運行 -
In [166]: a
Out[166]: array([0, 3, 2, 4, 0, 2, 3, 1, 1, 6, 2])
In [167]: W = 3
In [168]: np.maximum.reduceat(a,np.r_[:len(a):W])
Out[168]: array([3, 4, 3, 6])
方法#2
這是slicing
的另一個 -
def max_interval_slice(a, W=3):
n = len(a)//W
max0 = a[:n*W].reshape(-1,W).max(1)
if n*W==len(a):
return max0
else:
return np.r_[max0, np.max(a[n*W:])]
樣品運行 -
# Input array of length NOT multiple of width=3
In [99]: a
Out[99]: array([0, 3, 2, 4, 0, 2, 3, 1, 1, 6, 2])
In [100]: max_interval_slice(a, W=3)
Out[100]: array([3, 4, 3, 6])
# Input array of length multiple of width=3
In [95]: a = a[:9]
In [96]: max_interval_slice(a, W=3)
Out[96]: array([3, 4, 3])
首先使用np.pad
a = np.pad(a, [0, 1], mode='constant')
然后reshape
和max
>>> np.max(a.reshape(-1, 3), axis=1)
array([3, 4, 3, 6])
為了概括這一點,只需計算填充以重新形成所需的尺寸。
要最小化您需要執行的重新分配量,您可以計算適合3的倍數的所有元素的最大值,然后計算余數的最大值。 此解決方案不是那么簡單,但它不會創建不必要的數據副本:
n = 3 # The group width
prefix, suffix = divmod(a.size, n)
output = np.empty(prefix + bool(suffix))
a[:n * prefix].reshape(-1, n).max(axis=1, out=output[:prefix])
if suffix:
output[-1] = a[-suffix:].max()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.