我正在使用一個numpy.array
作爲數據緩衝區,我正在尋找一個優雅的方式來reframe
它,以便它保留一部分初始數據,這取決於新的幀條件(緩衝液可以具有shrunk
,expanded
,shifted
或shift
+ 2前的組合)如何優雅地「重構」一個numpy陣列
Reframe
可能不是這裏的合適術語。但下面的例子將有望更清晰:
爲了簡單起見,我將使用False
來說明一個空reframed
數組元素:
import numpy as np
# Init buffer
data = 10 * np.arange(6) + 10 # dummy data for this example
# Result: array([10, 20, 30, 40, 50, 60]) #
收縮的緩衝液:
# shift start by 1 to the right, and end by 1 to the left
reframe(data,1,-1) # basically doing: buffer[1:-1]
# Desired Result = array([20, 30, 40, 50]) #
展開緩衝器:
# shift start by 2 to the left, and end by 1 to the
reframe(data,-2,1)
# Desired Result: array([False, False, 10, 20, 30, 40, 50, 60, False]) #
將緩衝區左移或右移+擴大:
# shift start by 2 to the right, and end by 4 to the right
reframe(data,2,4)
# Desired Result: array([30, 40, 50, 60, False, False, False, False]) #
同樣,在這個例子中我使用False
其中我期望一個新的空reframed
數組元素。這可能是np.empty
,或np.NaN
,等...
爲了實現我的目標,我寫了以下內容:
import numpy as np
def reframe(data,start,end):
# Shrinking: new array is a substet of original
if start >= 0 and end <=0:
if start > 0 and end < 0:
return data[start:end]
if start > 0:
return data[start:]
return data[:end]
# Expand, new array fully contains original
elif start <= 0 and end >= 0:
new = np.zeros(data.shape[0] + end - start).astype(data.dtype)
new[abs(start):data.shape[0]+2] = data
return new
# Shift, new array may have a portion of old
else:
new = np.zeros((data.shape[0]-start+end)).astype(data.dtype)
# Shift Right
if start > 0:
new[:data.shape[0]-start] = data[start:]
return new
# Shift Left
if end < 0:
new[:data.shape[0]+end] = data[::-1][abs(end):]
return new[::-1]
測試:
print reframe(data,1,-1) # [20 30 40 50]
print reframe(data,-2,1) # [ 0 0 10 20 30 40 50 60 0]
print reframe(data,2,4) # [30 40 50 60 0 0 0 0]
所以此工程在我的目的,但我希望能有些更優雅的東西。
另外在我的現實生活中,我的數組有數十萬個,所以效率是必須的。
只適用於1D陣列,或者你也想「重構」ND陣列? – MSeifert
@MSeifert在我當前的用例中,我需要「重新構建」1d和2d數組,但在2d數組的情況下,我只關心它是否沿着第1軸。所以,如果你有一個只適用於1d數組的解決方案,我不介意沿着第1軸元素應用它的2D陣列 – Fnord