将numpy标量转换为简单的python类型

bte*_*tel 4 python numpy

我有一个带有单个值(标量)的numpy数组,我想将其转换为对应的Python数据类型.例如:

import numpy as np
a = np.array(3)
b = np.array('3')
Run Code Online (Sandbox Code Playgroud)

我可以将它们转换成intstr通过铸造:

a_int = int(a)
b_str = str(b)
Run Code Online (Sandbox Code Playgroud)

但我需要提前知道这些类型.我想转换a为一个整数和b一个没有显式类型检查的字符串.有没有一种简单的方法来实现它?

Mik*_*e T 7

如上所述这里,使用obj.item():

import numpy as np
a = np.array(3)
b = np.array('3')
print(type(a.item()))  # <class 'int'>
print(type(b.item()))  # <class 'str'>
Run Code Online (Sandbox Code Playgroud)


YXD*_*YXD 6

在这种情况下

import numpy as np
a = np.array(3)
b = np.array('3')
a_int = a.tolist()
b_str = b.tolist()
print type(a_int), type(b_str)
Run Code Online (Sandbox Code Playgroud)

应该管用