【问题标题】:python numpy assigning by boolean indexing error "TypeError: array cannot be safely cast to required type"python numpy通过布尔索引错误分配“TypeError:数组无法安全地转换为所需类型”
【发布时间】:2014-02-02 18:04:24
【问题描述】:

在以下代码的最后一行中,我收到“TypeError:数组无法安全地转换为所需类型”。你能帮忙吗?

让我稍微解释一下代码。 randin() 函数帮助我获得一个数组,其中的元素在lbub 指定的范围内。换句话说,你给randin()函数两个一维numpy数组lbub,它返回数组r,这个不等式适用于所有元素ilb[i] <= r[i] < ub[i]

在一维数组pos 中,某些元素可能超出lbub 指定的范围。我只想随机复制这些元素。如果可能的话,我想使用我已经存在的函数randin()。当然,我想使用花哨的布尔索引,而不是循环。

谢谢。

import numpy as np
def randin(lb, ub):
    """return random array with elements between the
    elements of lb and ub. ub is not included."""
    r = ((ub - lb) * np.random.random(np.shape(lb))
        + lb)
    return r

## inputs
pos = np.array([1, -3, 5, -7, 9, -11])
ub = np.ones_like(pos) * 5
lb = np.zeros_like(pos)

## reproduce and assign out of range elements
high = pos > ub
low = pos < lb
hl = high | low
pos[hl] = randin(lb[hl], ub[hl])

【问题讨论】:

  • 在我的win7,py2上,你的代码输出pos为array([1, 2, 5, 0, 0, 1]),无一例外
  • 适用于 linux,py2.7.5 也可以
  • 哼。我在win7上,我通过pythonxy发行版安装了py 2.7.3。我肯定会收到这个错误。更准确地说:Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32

标签: python arrays numpy indexing


【解决方案1】:

当我像pos = np.array([1, -3, 5, -7, 9, -11], dtype = float) 一样初始化pos 时,代码运行没有问题。所以 numpy 害怕将浮点数分配给整数元素。不错的主意。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-24
    • 2012-08-15
    • 1970-01-01
    • 2019-11-17
    • 2012-01-03
    • 1970-01-01
    • 2011-02-25
    • 2012-03-05
    相关资源
    最近更新 更多