在 Python 中向空数组添加一行

add a row to an empty array in python

提问人:diedro 提问时间:3/7/2023 更新时间:3/7/2023 访问量:50

问:

我会撒谎将数组添加到numpy中的空数组中。 基本上我想做以下事情:

AA = np.array([])


for i in range(0,3):
    # 
    BB = np.random.rand(3)
    CC = np.vstack((AA, BB))

但是,我收到以下错误:

all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 0 and the array at index 1 has size 3

我想避免引入 if 子句。一个想法可能是使用 “np.zeros(3)” 来设置 AA,然后删除第一行。

你觉得怎么样?我也喜欢第二种选择。

谢谢

python 数组为 vstack

评论

0赞 RomanPerekhrest 3/7/2023
当前状态下的代码是无意义的:是静态的,不会被改变AA

答:

0赞 Kroshtan 3/7/2023 #1

您可以使用创建具有设定大小的数组:np.empty

AA = np.empty((0, 3))

这给出了一个具有一个空维度和一个大小为 3 的维度的数组,因此可以使用您建议的数组。vstackBB

0赞 anomie87 3/7/2023 #2

你试过用代替吗?然后,您可以尝试以下操作:np.appendnp.vstack

AA = np.array([])

for i in range(0,3):
    BB = np.random.rand(3)
    # Use np.append to append BB to AA along the first axis
    AA = np.append(AA, BB)

# Reshape AA into a 2D array with 3 columns
AA = AA.reshape(-1, 3)

# AA should now contain the concatenated arrays