簡體   English   中英

Numpy - 用更快的東西替換 hstack/vstack if-loop(追加?)

[英]Numpy - Replacing hstack/vstack if-loop with something faster (append?)

我想將幾個(比如 15 個)長 arrays 形狀(3072,)組合成一個 np.array 形狀(15,3072)。 如果找到了解決方案,但是在 for 循環中包含嵌套的 if 子句,這對我來說似乎效率低下。 是否有更有效的解決方案來提出必要形狀的 numpy 陣列(而不是列表)? 這是代碼:

# Creating sample array
arr1 = np.array([8, 19, 43], dtype=int)

# What I do at the moment (and it works)
arr_out = np.array([])
for i in range(3):
    if i == 0:
        arr_out = np.hstack((arr_out, arr1))
    else:
        arr_out = np.vstack((arr_out, arr1))
        
arr_out # Output is correct shape (Each "new" array gets a new row.)

數組([[8., 19., 43.], [8., 19., 43.], [8., 19., 43.]])

當我使用 np.append 時會發生什么:

# How to do the above without the if loop in the for loop?
arr_out = np.array([])
for i in range(3):
    arr_out = np.append(arr_out, arr1, axis=0)

arr_out # Output is not in correct shape

數組([8., 19., 43., 8., 19., 43., 8., 19., 43.])

您是否看到不使用列表(或至少最終沒有列表)的第一個示例的 numpy.array 形狀的任何有效方法?

通過用我需要的正確數量的列初始化數組arr_out自己解決了這個問題(在上面的迷你示例中將是三個)。 然后您可以擺脫 if 子句並直接執行np.vstack 但是,當數組有很多列時(在我的實際情況下> 3000),在我看來,擺脫 if 子句的好處是初始化一個大的空數組。 因此,當您循環很多次時,擺脫 if 子句只會讓您在運行時方面做得更好(在我的情況下是這樣,因為我將運行大約 60.000 次)。 這是代碼:

# Creating sample array
arr1 = np.array([8, 19, 43], dtype=int)

# Solution
arr_out = np.array([0,len(arr1)])
for i in range(3): #I run through the loop a couple of thousand times
    arr_out = np.vstack((arr_out, arr1))

暫無
暫無

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

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