[英]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.