Python 追加到空的 NumPy 数组失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19646726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unsuccessful append to an empty NumPy array
提问by Cupitor
I am trying to fill an empty(not np.empty!) array with values using append but I am gettin error:
我正在尝试使用 append 用值填充一个空的(不是 np.empty!)数组,但我开始出现错误:
My code is as follows:
我的代码如下:
import numpy as np
result=np.asarray([np.asarray([]),np.asarray([])])
result[0]=np.append([result[0]],[1,2])
And I am getting:
我得到:
ValueError: could not broadcast input array from shape (2) into shape (0)
采纳答案by Bi Rico
numpy.append
is pretty different from list.append in python. I know that's thrown off a few programers new to numpy. numpy.append
is more like concatenate, it makes a new array and fills it with the values from the old array and the new value(s) to be appended. For example:
numpy.append
与 python 中的 list.append 有很大不同。我知道这让一些刚接触 numpy 的程序员感到厌烦。numpy.append
更像是连接,它创建一个新数组并用旧数组中的值和要附加的新值填充它。例如:
import numpy
old = numpy.array([1, 2, 3, 4])
new = numpy.append(old, 5)
print old
# [1, 2, 3, 4]
print new
# [1, 2, 3, 4, 5]
new = numpy.append(new, [6, 7])
print new
# [1, 2, 3, 4, 5, 6, 7]
I think you might be able to achieve your goal by doing something like:
我认为您可以通过执行以下操作来实现您的目标:
result = numpy.zeros((10,))
result[0:2] = [1, 2]
# Or
result = numpy.zeros((10, 2))
result[0, :] = [1, 2]
Update:
更新:
If you need to create a numpy array using loop, and you don't know ahead of time what the final size of the array will be, you can do something like:
如果您需要使用循环创建一个 numpy 数组,并且您不知道数组的最终大小是多少,您可以执行以下操作:
import numpy as np
a = np.array([0., 1.])
b = np.array([2., 3.])
temp = []
while True:
rnd = random.randint(0, 100)
if rnd > 50:
temp.append(a)
else:
temp.append(b)
if rnd == 0:
break
result = np.array(temp)
In my example result will be an (N, 2) array, where N is the number of times the loop ran, but obviously you can adjust it to your needs.
在我的示例中,结果将是一个 (N, 2) 数组,其中 N 是循环运行的次数,但显然您可以根据需要对其进行调整。
new update
新更新
The error you're seeing has nothing to do with types, it has to do with the shape of the numpy arrays you're trying to concatenate. If you do np.append(a, b)
the shapes of a
and b
need to match. If you append an (2, n) and (n,) you'll get a (3, n) array. Your code is trying to append a (1, 0) to a (2,). Those shapes don't match so you get an error.
您看到的错误与类型无关,它与您尝试连接的 numpy 数组的形状有关。如果你做np.append(a, b)
的形状a
和b
需要匹配。如果你附加一个 (2, n) 和 (n,) 你会得到一个 (3, n) 数组。您的代码试图将 (1, 0) 附加到 (2,)。这些形状不匹配,因此您会收到错误消息。
回答by Stuart Berg
numpy.append
always copies the array before appending the new values. Your code is equivalent to the following:
numpy.append
总是在追加新值之前复制数组。您的代码等效于以下内容:
import numpy as np
result = np.zeros((2,0))
new_result = np.append([result[0]],[1,2])
result[0] = new_result # ERROR: has shape (2,0), new_result has shape (2,)
Perhaps you mean to do this?
也许你的意思是这样做?
import numpy as np
result = np.zeros((2,0))
result = np.append([result[0]],[1,2])
回答by Alejandro
This error arise from the fact that you are trying to define an object of shape (0,) as an object of shape (2,). If you append what you want without forcing it to be equal to result[0] there is no any issue:
此错误源于您试图将形状 (0,) 的对象定义为形状 (2,) 的对象。如果您附加您想要的内容而不强制它等于 result[0] ,则没有任何问题:
b = np.append([result[0]], [1,2])
But when you define result[0] = b you are equating objects of different shapes, and you can not do this. What are you trying to do?
但是当您定义 result[0] = b 时,您将不同形状的对象等同起来,而您不能这样做。你想做什么?
回答by hpaulj
Here's the result of running your code in Ipython. Note that result
is a (2,0)
array, 2 rows, 0 columns, 0 elements. The append
produces a (2,)
array. result[0]
is (0,)
array. Your error message has to do with trying to assign that 2 item array into a size 0 slot. Since result
is dtype=float64
, only scalars can be assigned to its elements.
这是在 Ipython 中运行代码的结果。请注意,这result
是一个(2,0)
数组,2 行,0 列,0 个元素。在append
产生一个(2,)
阵列。 result[0]
是(0,)
数组。您的错误消息与尝试将该 2 项数组分配到大小为 0 的插槽有关。由于result
is dtype=float64
,只能为其元素分配标量。
In [65]: result=np.asarray([np.asarray([]),np.asarray([])])
In [66]: result
Out[66]: array([], shape=(2, 0), dtype=float64)
In [67]: result[0]
Out[67]: array([], dtype=float64)
In [68]: np.append(result[0],[1,2])
Out[68]: array([ 1., 2.])
np.array
is not a Python list. All elements of an array are the same type (as specified by the dtype
). Notice also that result
is not an array of arrays.
np.array
不是 Python 列表。数组的所有元素都是相同的类型(由 指定dtype
)。另请注意,这result
不是数组数组。
Result could also have been built as
结果也可以构建为
ll = [[],[]]
result = np.array(ll)
while
尽管
ll[0] = [1,2]
# ll = [[1,2],[]]
the same is not true for result.
结果并非如此。
np.zeros((2,0))
also produces your result
.
np.zeros((2,0))
还会生成您的result
.
Actually there's another quirk to result
.
实际上还有另一个怪癖result
。
result[0] = 1
does not change the values of result
. It accepts the assignment, but since it has 0 columns, there is no place to put the 1
. This assignment would work in result was created as np.zeros((2,1))
. But that still can't accept a list.
不改变 的值result
。它接受分配,但由于它有 0 列,因此没有地方放置1
. 此分配将在结果创建为np.zeros((2,1))
. 但这仍然不能接受列表。
But if result
has 2 columns, then you can assign a 2 element list to one of its rows.
但是如果result
有 2 列,那么您可以将一个 2 元素列表分配给其中的一行。
result = np.zeros((2,2))
result[0] # == [0,0]
result[0] = [1,2]
What exactly do you want result
to look like after the append
operation?
手术result
后你到底想变成什么样子append
?
回答by hpaulj
SO thread 'Multiply two arrays element wise, where one of the arrays has arrays as elements' has an example of constructing an array from arrays. If the subarrays are the same size, numpy makes a 2d array. But if they differ in length, it makes an array with dtype=object
, and the subarrays retain their identity.
SO thread '将两个数组元素相乘,其中一个数组将数组作为元素'有一个从数组构造数组的示例。如果子数组大小相同,则 numpy 会生成一个二维数组。但是如果它们的长度不同,它会生成一个带有 的数组dtype=object
,并且子数组保留它们的身份。
Following that, you could do something like this:
之后,您可以执行以下操作:
In [5]: result=np.array([np.zeros((1)),np.zeros((2))])
In [6]: result
Out[6]: array([array([ 0.]), array([ 0., 0.])], dtype=object)
In [7]: np.append([result[0]],[1,2])
Out[7]: array([ 0., 1., 2.])
In [8]: result[0]
Out[8]: array([ 0.])
In [9]: result[0]=np.append([result[0]],[1,2])
In [10]: result
Out[10]: array([array([ 0., 1., 2.]), array([ 0., 0.])], dtype=object)
However, I don't offhand see what advantages this has over a pure Python list or lists. It does not work like a 2d array. For example I have to use result[0][1]
, not result[0,1]
. If the subarrays are all the same length, I have to use np.array(result.tolist())
to produce a 2d array.
但是,我并没有立即看到它与纯 Python 列表相比有什么优势。它不像二维数组那样工作。例如,我必须使用result[0][1]
,而不是result[0,1]
. 如果子np.array(result.tolist())
数组的长度都相同,我必须使用它来生成二维数组。
回答by Simon Streicher
I might understand the question incorrectly, but if you want to declare an array of a certain shape but with nothing inside, the following might be helpful:
我可能会错误地理解这个问题,但是如果您想声明一个特定形状的数组,但里面没有任何内容,以下内容可能会有所帮助:
Initialise empty array:
初始化空数组:
>>> a = np.zeros((0,3)) #or np.empty((0,3)) or np.array([]).reshape(0,3)
>>> a
array([], shape=(0, 3), dtype=float64)
Now you can use this array to append rows of similar shape to it. Remember that a numpy array is immutable, so a new array is created for each iteration:
现在您可以使用此数组向其追加形状相似的行。请记住,numpy 数组是不可变的,因此每次迭代都会创建一个新数组:
>>> for i in range(3):
... a = np.vstack([a, [i,i,i]])
...
>>> a
array([[ 0., 0., 0.],
[ 1., 1., 1.],
[ 2., 2., 2.]])
np.vstack and np.hstack is the most common method for combining numpy arrays, but coming from Matlab I prefer np.r_ and np.c_:
np.vstack 和 np.hstack 是组合 numpy 数组最常用的方法,但来自 Matlab 我更喜欢 np.r_ 和 np.c_:
Concatenate 1d:
连接 1d:
>>> a = np.zeros(0)
>>> for i in range(3):
... a = np.r_[a, [i, i, i]]
...
>>> a
array([ 0., 0., 0., 1., 1., 1., 2., 2., 2.])
Concatenate rows:
连接行:
>>> a = np.zeros((0,3))
>>> for i in range(3):
... a = np.r_[a, [[i,i,i]]]
...
>>> a
array([[ 0., 0., 0.],
[ 1., 1., 1.],
[ 2., 2., 2.]])
Concatenate columns:
连接列:
>>> a = np.zeros((3,0))
>>> for i in range(3):
... a = np.c_[a, [[i],[i],[i]]]
...
>>> a
array([[ 0., 1., 2.],
[ 0., 1., 2.],
[ 0., 1., 2.]])