【发布时间】:2016-09-01 09:37:36
【问题描述】:
我需要生成一个包含重复元素的大数组,我的代码是:
np.repeat(xrange(x,y), data)
但是,data 是一个类型为 float64 的 numpy 数组(但它代表整数,那里没有 2.1),我得到了错误
TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe'
示例:
In [35]: x
Out[35]: 26
In [36]: y
Out[36]: 50
In [37]: data
Out[37]:
array([ 3269., 106., 5533., 317., 1512., 208., 502., 919.,
406., 421., 1690., 2236., 705., 505., 230., 213.,
307., 1628., 4389., 1491., 355., 103., 854., 424.])
In [38]: np.repeat(xrange(x,y), data)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-38-105860821359> in <module>()
----> 1 np.repeat(xrange(x,y), data)
/home/pcadmin/anaconda2/lib/python2.7/site-packages/numpy /core/fromnumeric.pyc in repeat(a, repeats, axis)
394 repeat = a.repeat
395 except AttributeError:
--> 396 return _wrapit(a, 'repeat', repeats, axis)
397 return repeat(repeats, axis)
398
/home/pcadmin/anaconda2/lib/python2.7/site-packages/numpy /core/fromnumeric.pyc in _wrapit(obj, method, *args, **kwds)
46 except AttributeError:
47 wrap = None
---> 48 result = getattr(asarray(obj), method)(*args, **kwds)
49 if wrap:
50 if not isinstance(result, mu.ndarray):
TypeError: Cannot cast array data from dtype('float64') to dtype('int64') according to the rule 'safe'
我通过将代码更改为来解决它
np.repeat(xrange(x,y), data.astype('int64'))
但是,这现在是我的代码中最昂贵的行之一!还有其他选择吗?
顺便说一下,我在里面用这个
np.random.choice(np.repeat(xrange(x,y), data.astype('int64')), z)
为了得到一个样本而不用替换 x 和 y 之间的整数的大小 z,每个样本的数量在数据中给出。我想这也是最好的方法吧?
【问题讨论】:
-
您能提供一个样例吗?那么,
x,y,data,z的一些示例值? -
如果您的数据是数组类型,您可以简单地将其包装在带有 dtype 集的 numpy 数组中,例如。
np.asarray(data, dtype='int64') -
对不起,我将在问题中进行编辑。 data 已经是一个 numpy 数组了
-
是的,但是为了使用
np.repeat,您必须将数据元素转换为 int 类型作为中继器。所以包装你的new_data = np.asarray(data, dtype='int64'); np.repeat(..., new_data) -
将数据作为一个非常大的数组(例如,>100000 个条目)比我的解决方案(data.astype("int64"))更好地处理 new_data ?
标签: python python-2.7 numpy casting repeat