2016-01-26 37 views
4

將數組擴展到特定大小的最有效方法是什麼?使用自己的內容將numpy數組擴展到特定範圍

import numpy as np 

# For this example, lets use an array with 4 items 
data = np.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11]]) # 4 items 

# I want to extend it to 10 items, here's the expected result would be: 
data = np.array([[ 0, 1, 2], 
       [ 3, 4, 5], 
       [ 6, 7, 8], 
       [ 9, 10, 11], 
       [ 0, 1, 2], 
       [ 3, 4, 5], 
       [ 6, 7, 8], 
       [ 9, 10, 11], 
       [ 0, 1, 2], 
       [ 3, 4, 5]]) 

回答

3

您可以連接陣列:

def extend_array(arr, length): 
    factor, fraction = divmod(length, len(arr)) 
    return np.concatenate([arr] * factor + [arr[:fraction]]) 

>>> extend_array(data, 10) 

array([[ 0, 1, 2], 
     [ 3, 4, 5], 
     [ 6, 7, 8], 
     [ 9, 10, 11], 
     [ 0, 1, 2], 
     [ 3, 4, 5], 
     [ 6, 7, 8], 
     [ 9, 10, 11], 
     [ 0, 1, 2], 
     [ 3, 4, 5]]) 
+0

快速更正,你想要'arr [:fraction]'。根據數組的大小,您的方法可以明顯更快,因爲重複的整個*塊被中間存儲爲對同一對象的引用。 – Reti43

+0

太棒了!是最後一項應該是arr [:fraction] – Fnord

+0

已更正。改了名字,忘了其中的一個。 –

1

我能想到的最有效的方法是使用itertools模塊。首先創建每一行的循環(無限迭代器),然後根據需要使用islice()獲取儘可能多的行。這樣的結果必須是元組或列表,因爲numpy requires the length of the array to be explicit at construction time

import itertools as it 

def extend_array(arr, length): 
    return np.array(tuple(it.islice(it.cycle(arr), length))) 

用法:

>>> data = np.array([[0,1,2],[3,4,5],[6,7,8],[9,10,11]]) 
>>> extend_array(data, 10) 
array([[ 0, 1, 2], 
     [ 3, 4, 5], 
     [ 6, 7, 8], 
     [ 9, 10, 11], 
     [ 0, 1, 2], 
     [ 3, 4, 5], 
     [ 6, 7, 8], 
     [ 9, 10, 11], 
     [ 0, 1, 2], 
     [ 3, 4, 5]]) 
+0

偉大的答案。謝謝! – Fnord

相關問題