将 numpy dtypes 转换为原生 python 类型 [英] Converting numpy dtypes to native python types

查看:27
本文介绍了将 numpy dtypes 转换为原生 python 类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I have a numpy dtype, how do I automatically convert it to its closest python data type? For example,

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

我可以尝试想出所有这些情况的映射,但是 numpy 是否提供了一些将其 dtypes 转换为最接近的本机 Python 类型的自动方法?此映射不必详尽无遗,但它应该转换具有接近 python 模拟的常见 dtype.我认为这已经发生在 numpy 的某个地方.

I could try to come up with a mapping of all of these cases, but does numpy provide some automatic way of converting its dtypes into the closest possible native python types? This mapping need not be exhaustive, but it should convert the common dtypes that have a close python analog. I think this already happens somewhere in numpy.

推荐答案

使用 val.item() 将大多数 NumPy 值转换为原生 Python 类型:

Use val.item() to convert most NumPy values to a native Python type:

import numpy as np

# for example, numpy.float32 -> python float
val = np.float32(0)
pyval = val.item()
print(type(pyval))         # <class 'float'>

# and similar...
type(np.float64(0).item()) # <class 'float'>
type(np.uint32(0).item())  # <class 'int'>
type(np.int16(0).item())   # <class 'int'>
type(np.cfloat(0).item())  # <class 'complex'>
type(np.datetime64(0, 'D').item())  # <class 'datetime.date'>
type(np.datetime64('2001-01-01 00:00:00').item())  # <class 'datetime.datetime'>
type(np.timedelta64(0, 'D').item()) # <class 'datetime.timedelta'>
...

(另一种方法是 np.asscalar(val),但是它从 NumPy 1.16 开始被弃用).

(Another method is np.asscalar(val), however it is deprecated since NumPy 1.16).

出于好奇,构建一个 NumPy 数组标量的转换表 对于您的系统:

For the curious, to build a table of conversions of NumPy array scalars for your system:

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

有一些 NumPy 类型在某些系统上没有原生 Python 等效项,包括:clongdoubleclongfloatcomplex192complex256float128longcomplexlongdoublelongfloat.在使用 .item() 之前,这些需要转换为最接近的 NumPy 等效项.

There are a few NumPy types that have no native Python equivalent on some systems, including: clongdouble, clongfloat, complex192, complex256, float128, longcomplex, longdouble and longfloat. These need to be converted to their nearest NumPy equivalent before using .item().

这篇关于将 numpy dtypes 转换为原生 python 类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆