未成功追加到空 NumPy 数组 [英] Unsuccessful append to an empty NumPy array

查看:25
本文介绍了未成功追加到空 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天全站免登陆