Conversión de dtypes numpy a tipos nativos de python


Si tengo un dtype numpy, ¿cómo lo convierto automáticamente a su tipo de datos python más cercano? Por ejemplo,

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

Podría intentar crear un mapeo de todos estos casos, pero ¿numpy proporciona alguna forma automática de convertir sus dtypes en los tipos nativos de python más cercanos posibles? Esta asignación no necesita ser exhaustiva, pero debería convertir los dtypes comunes que tienen un análogo de python cercano. Creo que esto ya sucede en algún lugar de Numpy.

 139
Author: conradlee, 2012-02-26

7 answers

Utilizar:a.item() o np.asscalar(a) para convertir la mayoría de los valores NumPy a un tipo Python nativo:

import numpy as np
# examples using a.item()
type(np.float32(0).item()) # <type 'float'>
type(np.float64(0).item()) # <type 'float'>
type(np.uint32(0).item())  # <type 'long'>
# examples using np.asscalar(a)
type(np.asscalar(np.int16(0)))   # <type 'int'>
type(np.asscalar(np.cfloat(0)))  # <type 'complex'>
type(np.asscalar(np.datetime64(0, 'D')))  # <type 'datetime.datetime'>
type(np.asscalar(np.timedelta64(0, 'D'))) # <type 'datetime.timedelta'>
...

Lea más en el manual NumPy. Para los curiosos, para construir una tabla de conversiones para su sistema:

for name in dir(np):
    obj = getattr(np, name)
    if hasattr(obj, 'dtype'):
        try:
            if 'time' in name:
                npn = obj(0, 'D')
            else:
                npn = obj(0)
            nat = npn.item()
            print('{0} ({1!r}) -> {2}'.format(name, npn.dtype.char, type(nat)))
        except:
            pass

Hay algunos tipos NumPy que no tienen equivalente nativo de Python en algunos sistemas, incluyendo: clongdouble, clongfloat, complex192, complex256, float128, longcomplex, longdouble y longfloat. Estos deben convertirse a su equivalente NumPy más cercano antes de usar asscalar.

 188
Author: Mike T,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-14 21:01:23

Me encontré con un conjunto mixto de tipos numpy y python estándar. como todos los tipos numpy derivan de numpy.generic, así es como puedes convertir todo a tipos estándar de python:

if isinstance(obj, numpy.generic):
    return numpy.asscalar(obj)
 30
Author: tm_lv,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-24 10:46:30

Qué tal:

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'>}
 9
Author: unutbu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-26 12:55:26

Si desea convertir (numpy.matriz O numpy escalar O tipo nativo O numpy.darray) AL tipo nativo simplemente puede hacer :

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

Tolist convertirá su escalar o matriz al tipo nativo de python. La función lambda predeterminada se encarga del caso en el que el valor ya es nativo.

 7
Author: v.thorey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-21 09:33:37

También puede llamar a la item() método del objeto que desea convertir:

>>> from numpy import float32, uint32
>>> type(float32(0).item())
<type 'float'>
>>> type(uint32(0).item())
<type 'long'>
 6
Author: Aryeh Leib Taurog,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-05 20:47:56

Creo que puedes escribir la función general type convert así:

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

Esto significa que no hay listas fijas y su código escalará con más tipos.

 4
Author: Matt Alcock,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-26 18:45:16

Numpy mantiene esa información en una asignación expuesta como typeDict para que pueda hacer algo como lo siguiente::

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

Si desea los tipos de python reales en lugar de sus nombres, puede hacer ::

>>> {v: getattr(__builtin__, k) for k, v in np.typeDict.items() if k in vars(__builtin__)}
{numpy.object_: object,
 numpy.bool_: bool,
 numpy.string_: str,
 numpy.unicode_: unicode,
 numpy.int64: int,
 numpy.float64: float,
 numpy.complex128: complex}
 1
Author: Meitham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-21 09:55:22