如何像C++一样更改python numpy指针类型?

l5tcr1uw  于 2023-05-17  发布在  Python
关注(0)|答案(1)|浏览(177)

我有一个numpy数组,它的shape是(2,),dtypenp.int64,比如说,

import numpy as np
a = np.empty((2,), dtype=np.int64)

现在,我想使用相同的内存区域,但将其dtype更改为np.int32。如果是C++,我可以写

#include <vector>
#include <cstdint>
using namespace std;
vector<int64_t> a(2);
int32_t* b = reinterpret_cast<int32_t*>(a.data());

事实上,我可以用python这样写

b = np.array(a, copy=False)
b.dtype = np.int32

我可以用这种方式做我想做的事。但是,如果我使用mypy检查代码,mypy将显示error: Property "dtype" defined in "ndarray" is read-only [misc]。我想知道在numpy中是否有更合适的方式来做我想做的事情?

pu3pd22g

pu3pd22g1#

是的,您可以在构造函数中指定dtype。

b = np.array(a, dtype=int)

此外,从1.24.0开始,np.int和类似的都被弃用。使用int
更改指针类型是危险的,因为内存保持连续,但实际数据占用的空间更少。你可以为此做一些跨步的技巧,但是为什么要这么麻烦呢?[有原因,但是你没有说任何关于它们的事情]?这不是C++,而且你通常只想复制。

相关问题