Numpy-用更快的东西(append?)替换hstack/vstack if循环



我想把几个(比如说15个(长的形状数组(3072,(组合成一个形状数组(153072(。如果找到了一个解决方案,但在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子句只会让你在运行时过得更好(在我的情况下是真的,因为我会运行它大约60000次(。这是代码:

# 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))

最新更新