Python 在for循环中将一个numpy数组添加到另一个numpy数组中
我必须:Python 在for循环中将一个numpy数组添加到另一个numpy数组中,python,arrays,numpy,Python,Arrays,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, 'am
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替代。。。我只是被困在这里!谢谢您真正需要的是
np.vstack()
函数。
它将按您希望的方式附加新数组。如果要附加的所有数组都有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,因此需要对其进行重塑。请让我知道这是否有效。这需要一些猜测工作,因为示例代码不完整,但您可能只需要:
filled_order_buy = df_all_orders.loc[1:, ['price', 'amount']].values
获取所需数据的二维NumPy数组。这将取代完整的for循环
根据代码中的下一步,可能您甚至不需要
.values
部分,只需使用结果数据帧作为下一步操作的输入。您的意思是什么?您必须提到如何塑造数组。。。我不知道有多少数组需要附加到我的数组中,因为我的数据非常长。我不理解你之前的消息。。。这是一个更大的代码的一部分,我只需要这样做..我只是更改了它,以便你在所有行中单步执行,除了第一行?正如我说过的,我已经尝试过了,两个数组需要有相同的维度我和以前有相同的问题:`所有的输入数组必须有相同数量的维度',明白了问题,输入数组的维数为(2,),使用(1,-1)对其进行重塑。我已经更新了答案。