2016-07-04 74 views
9

什麼是最後用零填充數組的pythonic方式是什麼?零墊numpy陣列

def pad(A, length): 
    ... 

A = np.array([1,2,3,4,5]) 
pad(A, 8) # expected : [1,2,3,4,5,0,0,0] 

在我的實際使用情況,其實我想墊陣列,以1024例的最接近倍數:1342 => 2048,3000 => 3072

回答

12

numpy.padconstant模式做了你需要什麼,在這裏我們可以傳遞一個元組的第二個參數告訴有多少個零墊在每個尺寸,例如一個(2, 3)將墊零點左側和零右側:

鑑於A爲:

A = np.array([1,2,3,4,5]) 

np.pad(A, (2, 3), 'constant') 
# array([0, 0, 1, 2, 3, 4, 5, 0, 0, 0]) 

它也可以以墊二維陣列numpy的通過使元組的元組作爲填充寬度,其德ES的((top, bottom), (left, right))格式:

A = np.array([[1,2],[3,4]]) 

np.pad(A, ((1,2),(2,1)), 'constant') 

#array([[0, 0, 0, 0, 0],   # 1 zero padded to the top 
#  [0, 0, 1, 2, 0],   # 2 zeros padded to the bottom 
#  [0, 0, 3, 4, 0],   # 2 zeros padded to the left 
#  [0, 0, 0, 0, 0],   # 1 zero padded to the right 
#  [0, 0, 0, 0, 0]]) 

對於你的情況,你指定左側爲零,並從模塊劃分計算右側墊:

B = np.pad(A, (0, 1024 - len(A)%1024), 'constant') 
B 
# array([1, 2, 3, ..., 0, 0, 0]) 
len(B) 
# 1024 

對於較大A

A = np.ones(3000) 
B = np.pad(A, (0, 1024 - len(A)%1024), 'constant') 
B 
# array([ 1., 1., 1., ..., 0., 0., 0.]) 

len(B) 
# 3072 
+0

謝謝!如果原始長度是3000,它是否工作? (然後填充的長度應該是3072) – Basj

+0

它應該,因爲這裏正確的填充長度是'1024'和'len(A)'的模塊餘數除以1024之間的差值。應該很容易測試。 – Psidom

2

這應該工作:

def pad(A, length): 
    arr = np.zeros(length) 
    arr[:len(A)] = A 
    return arr 

可能可以,如果你初始化一個空數組(np.empty(length))來獲得稍好的性能,然後在A和日補單獨使用,但我懷疑在大多數情況下加速會帶來額外的代碼複雜性。

要獲得價值墊最多,我想你可能只需要使用像divmod

n, remainder = divmod(len(A), 1024) 
n += bool(remainder) 

基本上,這只是計算出1024多少次將您的數組的長度(和該部門的其餘部分是什麼)。如果沒有剩餘,那麼你只需要n * 1024元素。如果有餘數,那麼你想要(n + 1) * 1024

全在一起:

def pad1024(A): 
    n, remainder = divmod(len(A), 1024) 
    n += bool(remainder) 
    arr = np.zeros(n * 1024) 
    arr[:len(A)] = A 
    return arr   
+0

謝謝!任何想法自動填充使長度的倍數1024?我在寫東西,但它非常不pythonic;) – Basj

+0

@Basj - 當然,檢查我的更新。我沒有測試它或任何東西,但我認爲它應該可以工作...... – mgilson

+0

這是'pad'的功能,但有很多鈴鐺(前,後,不同軸,其他填充模式)。 – hpaulj

1

您也可以使用numpy.pad

>>> A = np.array([1,2,3,4,5]) 
>>> npad = 8 - len(A) 
>>> np.pad(A, pad_width=npad, mode='constant', constant_values=0)[npad:] 
array([1, 2, 3, 4, 5, 0, 0, 0]) 

而且在功能:

def pad(A, npads): 
    _npads = npads - len(A) 
    return np.pad(A, pad_width=_npads, mode='constant', constant_values=0)[_npads:] 
2

np.pad

A = np.array([1, 2, 3, 4, 5]) 
A = np.pad(A, (0, length), mode='constant') 

關於您的使用案例,所需填充零點數可以計算爲length = len(A) + 1024 - 1024 % len(A)

2

供將來參考:

def padarray(A, size): 
    t = size - len(A) 
    return np.pad(A, pad_width=(0, t), mode='constant') 

padarray([1,2,3], 8)  # [1 2 3 0 0 0 0 0]