问题描述
我想将几个(比如 15 个)长数组 (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.,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.,43.,8.,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))