首页 > 解决方案 > 在 for 循环中将一个 numpy 数组添加到另一个 numpy 数组

问题描述

我必须数组:

input = np.array([])
filled_orders_buy = np.array([])

我的代码如下所示:

   for index, row in islice(df_all_orders.iterrows(), 1, df_all_orders.index[-1]): 
                input = np.array([df_all_orders.loc[index, 'price'],df_all_orders.loc[index, 'amount']])
                filled_orders_buy = np.append(filled_orders_buy,input)

我所拥有的是以下内容:

[1.08094e-03 3.70000e+01 1.07151e-03 1.50000e+01 1.08353e-03 1.50000e+01]

我需要的是:

[[1.08094e-0,3 3.70000e+01],[ 1.07151e-03, 1.50000e+01],[ 1.08353e-03 ,1.50000e+01]]

请不要将其作为重复项,因为我当然尝试了连接或 vstack 的替代方法......我只是被困在这里!谢谢

标签: pythonarraysnumpy

解决方案


如果要附加的所有数组都有 2 个元素,那么您可以这样做:

filled_orders_buy = np.empty((0,2), float)
for index, row in df_all_orders:
            input = np.array([df_all_orders.loc[index, 'price'],df_all_orders.loc[index, 'amount']]).reshape(1,-1)
            filled_orders_buy = np.append(filled_orders_buy,input, axis = 0)

轴 0 用于垂直附加数据,但为此您需要在空数组中具有相似的维度。因此np.empty

编辑:此外,您的输入数组的 (2,) 维是 1D,因此您需要对其进行整形。请让我知道这是否有效。


推荐阅读