数组的就地类型转换

数组的就地类型转换

本文介绍了NumPy 数组的就地类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个 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)

不复制数组.它很大.

without copying the array. It is big.

这样做的原因是我有两种算法来计算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)

要显示转换是就地转换,请注意将 from 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 数组的就地类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:28