簡體   English   中英

用函數中的新數組填充 numpy 數組的最快方法

[英]Fastest way to fill numpy array with new arrays from function

我有一個函數f(a)testarray中獲取一個條目並返回一個包含 5 個值的數組:

f(testarray[0])
#Output: array([[0, 1, 5, 3, 2]])

由於f(testarray[0])是實驗的結果,我想為testarray的每個條目運行這個函數f並將每個結果存儲在一個新的 NumPy 數組中。 我一直認為這會很簡單,只需使用一個帶有testarray長度的空 NumPy 數組並以下列方式保存結果:

N = 1000 #Number of entries of the testarray
test_result  = np.zeros([N, 5], dtype=int)

for i in testarray:
        test_result[i] = f(i)

當我運行它時,我沒有收到任何錯誤消息,而是收到無意義的結果(一半的test_result是空的,而其余的則充滿了難以置信的值)。 由於f()完美地適用於testarray的單個條目,我認為我將結果保存在test_result中的方式是錯誤的。 我在這里想念什么?

(我知道我可以將結果保存為列表,然后附加一個空列表,但是這種方法對於我想要運行該函數的大量時間來說太慢了)。

由於您似乎不了解索引,請堅持使用這種方法

alist = [f(i) for i in testarray]
arr = np.array(alist)

我可以展示如何一起使用行索引和 testarray 值,但這需要更多解釋。

您的問題可能會通過以下小示例重現:

testarray = np.array([5, 6, 7, 3, 1])

def f(x):
    return np.array([x * i for i in np.arange(1, 6)])

f(testarray[0])
# [ 5 10 15 20 25]

test_result = np.zeros([len(testarray), 5], dtype=int)  # len(testarray) or testarray.shape[0]

因此,正如hpaulj在評論中提到的,您必須小心如何使用索引:

for i in range(len(testarray)):
    test_result[i] = f(testarray[i])

# [[ 5 10 15 20 25]
#  [ 6 12 18 24 30]
#  [ 7 14 21 28 35]
#  [ 3  6  9 12 15]
#  [ 1  2  3  4  5]]

還有另一種情況,其中testarray是一個指定的索引數組,其中包含從0N的隨機整數以完全填充零數組,即test_result 對於這種情況,我們可以創建一個可重現的示例:

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

def f(x):
    return np.array([x * i for i in np.arange(1, 6)])

f(testarray[0])
# [ 4  8 12 16 20]

test_result = np.zeros([len(testarray), 5], dtype=int)

因此,使用您的循環將得到以下結果:

for i in testarray:
    test_result[i] = f(i)
# [[ 0  0  0  0  0]
#  [ 1  2  3  4  5]
#  [ 2  4  6  8 10]
#  [ 3  6  9 12 15]
#  [ 4  8 12 16 20]]

從這個循環可以理解,如果索引數組不是從0N ,零數組中的一些行將保持零(不變):

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

for i in testarray:
    test_result[i] = f(i)
# [[ 0  0  0  0  0]   # <--
#  [ 1  2  3  4  5]
#  [ 2  4  6  8 10]
#  [ 0  0  0  0  0]   # <--
#  [ 4  8 12 16 20]]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM