python - 重复 numpy 值并指定 dtype

标签 python arrays numpy

我想生成一个如下形式的 numpy 数组:

0.5*[[0, 0], [1, 1], [2, 2], ...]

我希望最终数组的 dtypenumpy.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/

相关文章:

python - 加权选择简短而简单

python - 在 Python 3 中捕获特定的 OSError 异常

python , Pandas : return highest values from multiindex

python - 是否可以在不使用 sleep 条件的情况下使 gRPC 服务器保持事件状态?

java - 在对象数组中存储值,但有 2 个 Java 方法

Javascript - 数组覆盖

python - Pandas 数据框中整个列的子字符串

javascript - 按值合并对象,在数组中保留唯一值

Python:从命令行传递库函数

python - 使用字符串格式的 numpy 数组