如果我有一个numpy dtype,我如何自动将其转换为最接近的python数据类型?例如,

numpy.float32 -> "python float"
numpy.float64 -> "python float"
numpy.uint32  -> "python int"
numpy.int16   -> "python int"

我可以尝试提出所有这些情况的映射,但是numpy是否提供了一些自动的方法来将其dtypes转换为尽可能接近的本机python类型?这种映射不需要是详尽的,但它应该转换具有类似python的常见dtype。我想这已经在numpy的某个地方发生了。


当前回答

我的方法有点强硬,但似乎适用于所有情况:

def type_np2py(dtype=None, arr=None):
    '''Return the closest python type for a given numpy dtype'''

    if ((dtype is None and arr is None) or
        (dtype is not None and arr is not None)):
        raise ValueError(
            "Provide either keyword argument `dtype` or `arr`: a numpy dtype or a numpy array.")

    if dtype is None:
        dtype = arr.dtype

    #1) Make a single-entry numpy array of the same dtype
    #2) force the array into a python 'object' dtype
    #3) the array entry should now be the closest python type
    single_entry = np.empty([1], dtype=dtype).astype(object)

    return type(single_entry[0])

用法:

>>> type_np2py(int)
<class 'int'>

>>> type_np2py(np.int)
<class 'int'>

>>> type_np2py(str)
<class 'str'>

>>> type_np2py(arr=np.array(['hello']))
<class 'str'>

>>> type_np2py(arr=np.array([1,2,3]))
<class 'int'>

>>> type_np2py(arr=np.array([1.,2.,3.]))
<class 'float'>

其他回答

你也可以调用你想转换的对象的item()方法:

>>> from numpy import float32, uint32
>>> type(float32(0).item())
<type 'float'>
>>> type(uint32(0).item())
<type 'long'>

对不起,这部分来晚了,但我正在寻找一个转换numpy的问题。float64只适用于常规Python浮点数。我看到了3种方法:

npValue.item () npValue.astype(浮动) 浮动(npValue)

以下是IPython的相关计时:

In [1]: import numpy as np

In [2]: aa = np.random.uniform(0, 1, 1000000)

In [3]: %timeit map(float, aa)
10 loops, best of 3: 117 ms per loop

In [4]: %timeit map(lambda x: x.astype(float), aa)
1 loop, best of 3: 780 ms per loop

In [5]: %timeit map(lambda x: x.item(), aa)
1 loop, best of 3: 475 ms per loop

听起来float(npValue)似乎更快。

如果你想转换(numpy。数组或numpy标量或本机类型或numpy.darray)本机类型你可以简单地做:

converted_value = getattr(value, "tolist", lambda: value)()

Tolist会将标量或数组转换为python原生类型。默认的lambda函数处理值已经是本机的情况。

numpy将该信息保存在一个暴露为typeDict的映射中,因此您可以执行如下操作:

>>> import __builtin__ as builtins  # if python2
>>> import builtins                 # if python3

然后::

>>> import numpy as np
>>> {v: k for k, v in np.typeDict.items() if k in dir(builtins)}
{numpy.object_: 'object',
 numpy.bool_: 'bool',
 numpy.string_: 'str',
 numpy.unicode_: 'unicode',
 numpy.int64: 'int',
 numpy.float64: 'float',
 numpy.complex128: 'complex'}

如果你想要实际的python类型,而不是它们的名称,你可以执行::

>>> {v: getattr(builtins, k) for k, v in np.typeDict.items() if k in vars(builtins)}
{numpy.object_: object,
 numpy.bool_: bool,
 numpy.string_: str,
 numpy.unicode_: unicode,
 numpy.int64: int,
 numpy.float64: float,
 numpy.complex128: complex}

我发现自己混合使用了numpy类型和标准python。因为所有numpy类型都派生自numpy。泛型,下面是如何将所有内容转换为python标准类型:

if isinstance(obj, numpy.generic):
    return numpy.asscalar(obj)