如果我有一个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的某个地方发生了。


当前回答

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

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

其他回答

如何:

In [51]: dict([(d, type(np.zeros(1,d).tolist()[0])) for d in (np.float32,np.float64,np.uint32, np.int16)])
Out[51]: 
{<type 'numpy.int16'>: <type 'int'>,
 <type 'numpy.uint32'>: <type 'long'>,
 <type 'numpy.float32'>: <type 'float'>,
 <type 'numpy.float64'>: <type 'float'>}

我认为你可以像这样写一般类型的转换函数:

import numpy as np

def get_type_convert(np_type):
   convert_type = type(np.zeros(1,np_type).tolist()[0])
   return (np_type, convert_type)

print get_type_convert(np.float32)
>> (<type 'numpy.float32'>, <type 'float'>)

print get_type_convert(np.float64)
>> (<type 'numpy.float64'>, <type 'float'>)

这意味着没有固定的列表,您的代码将扩展到更多类型。

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

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

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

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

对不起,这部分来晚了,但我正在寻找一个转换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)似乎更快。