Преобразование numpy dtypes в собственные типы python

Если у меня есть numpy dtype, как мне автоматически преобразовать его в ближайший к нему тип данных python? Например,

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

я мог бы попытаться найти отображение всех в этих случаях, но предоставляет ли numpy некоторый автоматический способ преобразования своих dtypes в наиболее близкие из возможных нативных типов python? Это сопоставление не должно быть исчерпывающим, но оно должно преобразовывать общие dtypes, которые имеют близкий аналог python. Я думаю, что это уже происходит где-то в numpy.

198
задан conradlee 7 September 2016 в 23:37
поделиться

1 ответ

Мой подход немного силен, но, похоже, хорошо подходит для всех случаев:

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'>
1
ответ дан 23 November 2019 в 05:12
поделиться
Другие вопросы по тегам:

Похожие вопросы: