【发布时间】:2014-02-02 18:04:24
【问题描述】:
在以下代码的最后一行中,我收到“TypeError:数组无法安全地转换为所需类型”。你能帮忙吗?
让我稍微解释一下代码。 randin() 函数帮助我获得一个数组,其中的元素在lb 和ub 指定的范围内。换句话说,你给randin()函数两个一维numpy数组lb和ub,它返回数组r,这个不等式适用于所有元素i:lb[i] <= r[i] < ub[i]
在一维数组pos 中,某些元素可能超出lb 和ub 指定的范围。我只想随机复制这些元素。如果可能的话,我想使用我已经存在的函数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