向空NumPy数组追加失败 [英] Unsuccessful append to an empty NumPy array

查看:99
本文介绍了向空NumPy数组追加失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用append值填充一个空的(不是np.empty!)数组,但我却报错:

I am trying to fill an empty(not np.empty!) array with values using append but I am gettin error:

我的代码如下:

import numpy as np
result=np.asarray([np.asarray([]),np.asarray([])])
result[0]=np.append([result[0]],[1,2])

我得到了:

ValueError: could not broadcast input array from shape (2) into shape (0)

推荐答案

numpy.append与python中的list.append完全不同.我知道这已经摆脱了numpy的一些新程序员. numpy.append更像是连接,它创建一个新数组,并用旧数组中的值和要附加的新值填充它.例如:

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:

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]

更新:

如果需要使用循环创建一个numpy数组,并且您不提前知道数组的最终大小,可以执行以下操作:

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:

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)

在我的示例中,结果将是一个(N,2)数组,其中N是循环运行的次数,但是显然您可以根据需要进行调整.

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.

新更新

您看到的错误与类型无关,它与您要连接的numpy数组的形状有关.如果执行np.append(a, b),则ab的形状需要匹配.如果附加(2,n)和(n,),则会得到(3,n)数组.您的代码试图将(1,0)附加到(2,).这些形状不匹配,所以会出现错误.

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数组追加失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆