numpy `astype(int)` 返回 `np.int64` 而不是 `int` - 该怎么办?
我有一个标准的 np.array
,类型是 np.int32
:
idx = array([ 607, 638, 639, ..., 9279, 9317, 9318], dtype=int32)
为了确认 int32
确实是 np.int32
,我用以下方法检查:
>>> type(idx[0])
<class 'numpy.int32'>
之后,我想在后面使用这个数组,需要把它们转换成 int
类型(原因是我想用 cppyy
来索引一个 std::vector<T>
,而这个索引类型似乎要求比较严格)。所以我想我可以这样做:
>>> idx2 = idx.astype(int)
但是这样会得到:
>>> type(idx2[0])
<class 'numpy.int64'>
我是不是必须用类似这样的方式?
>>> idx3 = [int(k) for k in idx]
>>> type(idx3[0])
<class 'int'>
有没有什么建议?
更新 1:也许这能提供一些关于 std::vector
索引的更多信息:
>>> v[idx[0]]
*** TypeError: an integer is required
而且
>>> v[int(idx[0])]
<cppyy.gbl.std.vector<double> object at 0x559a9a8845a8>
更新 2:对我来说,转换成列表是可以接受的,我已经接受了这个答案。
2 个回答
0
如果你想保留numpy数组,可以把int32/int64转换成object
类型:
test_array = np.arange(10).astype(object)
print(type(test_array[0]))
<class 'int'>
补充说明:有趣的是,你不能把它当作索引来使用。这会产生错误:
test_array[test_array]
{IndexError}arrays used as indices must be of integer (or boolean) type
1
如果我理解正确的话,你可以使用 .tolist()
这个方法:
idx = np.array([607, 638, 939], dtype=np.int32)
idx3 = idx.tolist()
print(type(idx3[0]))
输出结果是:
<class 'int'>