[英]What is the fastest way to stack numpy arrays in a loop?
我有一個代碼在for
循環中生成我兩個 numpy arrays ( data_transform
)。 在第一個循環中生成一個(40, 2)
的 numpy 數組,在第二個循環中生成一個(175, 2)
。 我想將這兩個 arrays 連接成一個,給我一個(215, 2)
的數組。 我嘗試使用np.concatenate
和np.append
,但它給了我一個錯誤,因為 arrays 必須是相同的大小。 這是我如何執行代碼的示例:
result_arr = np.array([])
for label in labels_set:
data = [index for index, value in enumerate(labels_list) if value == label]
for i in data:
sub_corpus.append(corpus[i])
data_sub_tfidf = vec.fit_transform(sub_corpus)
data_transform = pca.fit_transform(data_sub_tfidf)
#Append array
sub_corpus = []
我也使用np.row_stack
但沒有其他東西給我一個(175, 2)
的值,這是我要連接的第二個數組。
@hpaulj 想說什么
在循環時堅持使用列表 append。
是
#use a normal list
result_arr = []
for label in labels_set:
data_transform = pca.fit_transform(data_sub_tfidf)
# append the data_transform object to that list
# Note: this is not np.append(), which is slow here
result_arr.append(data_transform)
# and stack it after the loop
# This prevents slow memory allocation in the loop.
# So only one large chunk of memory is allocated since
# the final size of the concatenated array is known.
result_arr = np.concatenate(result_arr)
# or
result_arr = np.stack(result_arr, axis=0)
# or
result_arr = np.vstack(result_arr)
您的 arrays 並沒有真正的不同尺寸。 它們有一個不同的維度,另一個是相同的。 在這種情況下,您始終可以沿“不同”維度堆疊。
使用連接,初始化“c”:
a = np.array([[8,3,1],[2,5,1],[6,5,2]])
b = np.array([[2,5,1],[2,5,2]])
matrix = [a,b]
c = np.empty([0,matrix[0].shape[1]])
for v in matrix:
c = np.append(c, v, axis=0)
Output:
[[8. 3. 1.]
[2. 5. 1.]
[6. 5. 2.]
[2. 5. 1.]
[2. 5. 2.]]
如果您有一個大小為(40, 2)
的數組a
和一個大小為(175,2)
的數組b
,您可以使用np.concatenate([a,b])
簡單地獲得一個大小為(215, 2)
的最終數組.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.