NumPy数组的就地类型转换 [英] In-place type conversion of a NumPy array
问题描述
给出一个int32
的NumPy数组,如何将它转换为float32
?所以基本上,我想做
Given a NumPy array of int32
, how do I convert it to float32
in place? So basically, I would like to do
a = a.astype(numpy.float32)
,不复制数组.很大.
之所以这样做,是因为我有两种算法来计算a
.其中一个返回一个数组int32
,另一个返回一个数组float32
(这是两种不同算法所固有的).所有进一步的计算都假定a
是float32
的数组.
The reason for doing this is that I have two algorithms for the computation of a
. One of them returns an array of int32
, the other returns an array of float32
(and this is inherent to the two different algorithms). All further computations assume that a
is an array of float32
.
当前,我在通过ctypes
调用的C函数中进行转换.有没有办法在Python中做到这一点?
Currently I do the conversion in a C function called via ctypes
. Is there a way to do this in Python?
推荐答案
您可以创建具有不同dtype的视图,然后就地复制到该视图中:
You can make a view with a different dtype, and then copy in-place into the view:
import numpy as np
x = np.arange(10, dtype='int32')
y = x.view('float32')
y[:] = x
print(y)
收益
array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.], dtype=float32)
要显示转换已就位,请注意将从 x
复制到y
会更改x
:
To show the conversion was in-place, note that copying from x
to y
altered x
:
print(x)
打印
array([ 0, 1065353216, 1073741824, 1077936128, 1082130432,
1084227584, 1086324736, 1088421888, 1090519040, 1091567616])
这篇关于NumPy数组的就地类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!