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


当前回答

翻译整个ndarray而不是一个单位数据对象:

def trans(data):
"""
translate numpy.int/float into python native data type
"""
result = []
for i in data.index:
    # i = data.index[0]
    d0 = data.iloc[i].values
    d = []
    for j in d0:
        if 'int' in str(type(j)):
            res = j.item() if 'item' in dir(j) else j
        elif 'float' in str(type(j)):
            res = j.item() if 'item' in dir(j) else j
        else:
            res = j
        d.append(res)
    d = tuple(d)
    result.append(d)
result = tuple(result)
return result

但是,当处理大型数据帧时,需要花费一些时间。我也在寻找一个更有效的解决方案。 希望有更好的答案。

其他回答

Tolist()是一种更通用的实现方法。它适用于任何基元dtype,也适用于数组或矩阵。

如果从基本类型调用I,实际上不会产生一个列表:

numpy = 1.15.2

>>> import numpy as np

>>> np_float = np.float64(1.23)
>>> print(type(np_float), np_float)
<class 'numpy.float64'> 1.23

>>> listed_np_float = np_float.tolist()
>>> print(type(listed_np_float), listed_np_float)
<class 'float'> 1.23

>>> np_array = np.array([[1,2,3.], [4,5,6.]])
>>> print(type(np_array), np_array)
<class 'numpy.ndarray'> [[1. 2. 3.]
 [4. 5. 6.]]

>>> listed_np_array = np_array.tolist()
>>> print(type(listed_np_array), listed_np_array)
<class 'list'> [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]

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的问题。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类型的数组list_numpy_numbers,执行以下操作:

list_native_numbers = [i.item() for i in list_numpy_numbers]

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

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'>)

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