我想生成一个如下形式的 numpy 数组:
0.5*[[0, 0], [1, 1], [2, 2], ...]
我希望最终数组的 dtype
为 numpy.float32
。
这是我的尝试:
>>> import numpy as np
>>> N = 5
>>> x = np.array(np.repeat(0.5*np.arange(N), 2), np.float32)
>>> x
array([ 0. , 0. , 0.5, 0.5, 1. , 1. , 1.5, 1.5, 2. , 2. ], dtype=float32)
这样好吗?我可以避免复制(如果它确实是复制)只是为了类型转换吗?
最佳答案
您只需 reshape 最终结果即可获得您想要的:
x = x.reshape(-1, 2)
你也可以通过 dtype
运行 arange
:
x = np.repeat(0.5*np.arange(N, dtype=np.float32), 2).reshape(-1, 2)
您可以使用 astype
方法轻松地将数组转换为另一种类型,该方法接受参数 copy
:
x.astype(np.int8, copy=False)
但是,as explained in the documentation , numpy
检查一些要求以返回 View 。如果不满足这些要求,则返回副本。
您可以通过检查 OWNDATA
属性来检查给定数组是另一个数组的副本还是 View ,该属性可通过 ndarray< 的
.flags
属性访问
编辑:更多关于检查给定数组是否为副本的信息......
关于python - 重复 numpy 值并指定 dtype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19812717/