将numpy.array附加到存储在列表中的某个numpy.array [英] Append a numpy.array to a certain numpy.array stored in a list
问题描述
我已经努力了几个小时,以了解为什么我无法做到这一点:
I have been for hours strugling to understand why i am not able to do this:
>>> import numpy as np
>>> a = [np.empty((0,78,3)) for i in range(2)]
>>> b = np.random.randint(10,size=(1,78,3))
>>> a[0] = np.append(a[0],[b],axis=0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/site-packages/numpy/lib/function_base.py", line 5003, in append
return concatenate((arr, values), axis=axis)
ValueError: all the input arrays must have same number of dimensions
>>>
a
是一个列表,其中包含s个形状为(0,78,3)的空numpy数组
a
is a list with s empty numpy arrays of shape (0,78,3)
b
是形状为(1,78,3)的随机numpy.array
b
is a random numpy.array with shape (1,78,3)
然后我尝试将b
追加到a[0]
...,但是由于尺寸不一而似乎不可行?..我不确定这里的问题是什么..如果我删除了列表部分会起作用,所以为什么不使用列表呢?.
I then try to append b
to a[0]
... but this doesn't seem to be possible because of not having same dimension?.. I am not sure whats the problem here.. if I removed the list part it would work, so why not with the list?..
推荐答案
远离np.append
.学习正确使用np.concatenate
.此附件只会造成混乱.
Stay away from np.append
. Learn to use np.concatenate
correctly. This append just creates confusion.
给出您的定义,此方法有效:
Given your definitions, this works:
In [20]: a1 = [np.concatenate((i,b),axis=0) for i in a]
In [21]: [i.shape for i in a1]
Out[21]: [(1, 78, 3), (1, 78, 3)]
In [22]: a
Out[22]:
[array([], shape=(0, 78, 3), dtype=float64),
array([], shape=(0, 78, 3), dtype=float64)]
In [23]: b.shape
Out[23]: (1, 78, 3)
In [24]: a1 = [np.concatenate((i,b),axis=0) for i in a]
In [25]: [i.shape for i in a1]
Out[25]: [(1, 78, 3), (1, 78, 3)]
(0,78,3)可以在轴0上与(1,78,3)数组连接,从而生成另一个(1,78,3)数组.
A (0,78,3) can concatenate on axis 0 with a (1,78,3) array, producing another (1,78,3) array.
但是为什么呢?它只是列出包含2个b
副本的列表.
But why do it? It just makes a list with 2 copies of b
.
c = [b,b]
这样做也更简单.
如果必须收集许多形状为(78,3)的数组,请
If you must collect many arrays of shape (78,3), do
alist = []
for _ in range(n):
alist.append(np.ones((78,3)))
n个数组的结果列表可以用
The resulting list of n arrays can be turned into an array with
np.array(alist) # (n, 78, 3) array
或者,如果您收集(1,78,3)数组的列表,则np.concatenate(alist, axis=0)
会将它们加入(n,78,3)数组中.
Or if you collect a list of (1,78,3) arrays, np.concatenate(alist, axis=0)
will join them into the (n,78,3) array.
这篇关于将numpy.array附加到存储在列表中的某个numpy.array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!