简体   繁体   English

附加 arrays 的 numpy 数组

[英]Appending numpy array of arrays

I am trying to append an array to another array but its appending them as if it was just one array.我正在尝试将 append 一个数组添加到另一个数组,但它会将它们附加到另一个数组中,就好像它只是一个数组一样。 What I would like to have is have each array appended on its own index, (withoug having to use a list, i want to use np arrays) ie我想要的是每个数组都附加在自己的索引上,(不必使用列表,我想使用 np 数组)即

temp = np.array([])
for i in my_items
   m = get_item_ids(i.color)  #returns an array as [1,4,20,5,3]  (always same number of items but diff ids
   temp = np.append(temp, m, axis=0)

On the second iteration lets suppose i get [5,4,15,3,10]在第二次迭代中,假设我得到 [5,4,15,3,10]

then i would like to have temp as array([1,4,20,5,3][5,4,15,3,10]) But instead i keep getting [1,4,20,5,3,5,4,15,3,10]然后我想将 temp 作为array([1,4,20,5,3][5,4,15,3,10])但是我一直得到[1,4,20,5,3,5,4,15,3,10]

I am new to python but i am sure there is probably a way to concatenate in this way with numpy without using lists?我是 python 的新手,但我确信可能有一种方法可以在不使用列表的情况下以这种方式与 numpy 连接?

You have to reshape m in order to have two dimension with您必须重塑 m 才能拥有二维

m.reshape(-1, 1)

thus adding the second dimension.从而增加了第二个维度。 Then you could concatenate along axis=1.然后你可以沿着axis = 1连接。

np.concatenate(temp, m, axis=1)

List append is much better - faster and easier to use correctly.列表 append更好- 更快,更容易正确使用。

temp = []
for i in my_items
    m = get_item_ids(i.color)  #returns an array as [1,4,20,5,3]  (always same number of items but diff ids
    temp = m

Look at the list to see what it created.查看列表以查看它创建的内容。 Then make an array from that:然后从中制作一个数组:

 arr = np.array(temp)
 # or `np.vstack(temp)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM