I am trying to fill an empty(not np.empty!) array with values using append but I am gettin error:
我试图用附加的值填充一个空的(不是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)
6 个解决方案
#1
30
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与list非常不同。附加在python中。我知道,这已经被一些新编程器抛弃了。numpy。append更像连接,它创建一个新的数组,并将旧数组的值和新值(s)填充到该数组中。例如:
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。附加(a, b) a和b的形状需要匹配。如果你附加一个(2,n)和(n,)你会得到一个(3,n)数组。您的代码试图将a(1,0)附加到(2)。那些形状不匹配,所以你会得到一个错误。
#2
54
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.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:
连接1 d:
>>> a = np.array([])
>>> 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.array([]).reshape(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.array([]).reshape(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.]])
#3
3
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,)。如果你在不强迫它等于结果的情况下附加你想要的结果[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?
但是当你定义结果[0]= b时,你就等于把不同形状的物体等同起来,你不能这样做。你想做什么?
#4
3
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中运行代码的结果。注意,结果是一个(2,0)数组,2行,0列,0个元素。append生成一个(2)数组。结果是[0](0)数组。您的错误消息与试图将该2项数组分配到一个大小为0的槽中有关。由于结果是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。数组不是Python列表。数组的所有元素都是相同的类型(由dtype指定)。注意,结果不是数组的数组。
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
.
0((2,0))也会产生结果。
Actually there's another quirk to 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.
不改变结果的值。它接受赋值,但由于它有0列,所以没有位置放置1。这个赋值将在结果中被创建为np0((2,1))。但这仍然不能接受一个列表。
But if result
has 2 columns, then you can assign a 2 element list to one of its rows.
但是如果结果有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?
在append操作之后,您想要得到什么样的结果?
#5
2
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])
#6
1
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.
因此,线程将两个数组元素相乘,其中一个数组中有数组作为元素,它有一个从数组构造数组的例子。如果子数组大小相同,numpy会生成一个2d数组。但是如果它们的长度不同,它就会使用dtype=对象进行数组,而子数组保留它们的标识。
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列表或列表上有什么优势。它不像2d数组那样工作。例如,我必须使用result[0][1],而不是result[0,1]。如果子数组的长度相同,那么我必须使用np.array(result.tolist())来生成一个2d数组。
#1
30
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与list非常不同。附加在python中。我知道,这已经被一些新编程器抛弃了。numpy。append更像连接,它创建一个新的数组,并将旧数组的值和新值(s)填充到该数组中。例如:
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。附加(a, b) a和b的形状需要匹配。如果你附加一个(2,n)和(n,)你会得到一个(3,n)数组。您的代码试图将a(1,0)附加到(2)。那些形状不匹配,所以你会得到一个错误。
#2
54
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.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:
连接1 d:
>>> a = np.array([])
>>> 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.array([]).reshape(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.array([]).reshape(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.]])
#3
3
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,)。如果你在不强迫它等于结果的情况下附加你想要的结果[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?
但是当你定义结果[0]= b时,你就等于把不同形状的物体等同起来,你不能这样做。你想做什么?
#4
3
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中运行代码的结果。注意,结果是一个(2,0)数组,2行,0列,0个元素。append生成一个(2)数组。结果是[0](0)数组。您的错误消息与试图将该2项数组分配到一个大小为0的槽中有关。由于结果是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。数组不是Python列表。数组的所有元素都是相同的类型(由dtype指定)。注意,结果不是数组的数组。
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
.
0((2,0))也会产生结果。
Actually there's another quirk to 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.
不改变结果的值。它接受赋值,但由于它有0列,所以没有位置放置1。这个赋值将在结果中被创建为np0((2,1))。但这仍然不能接受一个列表。
But if result
has 2 columns, then you can assign a 2 element list to one of its rows.
但是如果结果有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?
在append操作之后,您想要得到什么样的结果?
#5
2
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])
#6
1
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.
因此,线程将两个数组元素相乘,其中一个数组中有数组作为元素,它有一个从数组构造数组的例子。如果子数组大小相同,numpy会生成一个2d数组。但是如果它们的长度不同,它就会使用dtype=对象进行数组,而子数组保留它们的标识。
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列表或列表上有什么优势。它不像2d数组那样工作。例如,我必须使用result[0][1],而不是result[0,1]。如果子数组的长度相同,那么我必须使用np.array(result.tolist())来生成一个2d数组。