重复numpy的值,并指定DTYPE [英] Repeating numpy values and specifying dtype
问题描述
我要生成表单的numpy的数组:
I want to generate a numpy array of the form:
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)
这是一个好办法吗?我能避免复印件(如果它确实是复制)只是类型转换?
Is this a good way? Can I avoid the copy (if it is indeed copying) just for type conversion?
推荐答案
您只需要重塑你的最终结果,以获得你想要什么:
You only has to reshape your final result to obtain what you want:
x = x.reshape(-1, 2)
不过,您也可以运行人气指数
通过了 DTYPE
:
x = np.repeat(0.5*np.arange(N, dtype=np.float32), 2).reshape(-1, 2)
您可以使用 astype
方法,它接受一个参数易于铸造数组作为另一种类型的复制
:
You can easily cast the array as another type using the astype
method, which accepts an argument copy
:
x.astype(np.int8, copy=False)
但是,如文档中解释, numpy的
检查,以返回视图中的某些要求。如果这些要求未得到满足的副本被返回。
But, as explained in the documentation, numpy
checks for some requirements in order to return the view. If those requirements are not satisfied a copy is returned.
您可以检查是否给定的数组是一个副本,或通过检查从另一个视图中的 OWNDATA
属性访问通过标记
的属性 ndarray
。
You can check if a given array is a copy or a view from another by checking the OWNDATA
attribute accessible through the flags
property of the ndarray
.
编辑:更多的检查,如果给定的数组是一个副本...
more on checking if a given array is a copy...
- Is there a way to check if numpy arrays share the same data?
这篇关于重复numpy的值,并指定DTYPE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!