python - 在 Python 中将数组(numpy 数据类型)转换为元组( native 数据类型)

标签 python arrays numpy data-structures tuples

如何有效地转换 numpy.float64 的数组到 float 的元组的元组

输入是

a = array([array([1.]), array([2, 3]), array(['a', 'b', 'c'])])

其中值为 numpy基本类型,例如 numpy.float64 , numpy.int32 , numpy.str_

输出是

((1.,), (2, 3), ('a', 'b', 'c'))

其中值是原生类型 float , int , str , ...

我想可能有递归和迭代的方法……有什么想法吗?

最佳答案

拥有一个由不同大小和类型的数组组成的 numpy 数组通常表明您的设计出现了问题。但是,如果您出于某种原因得到了它,则可以使用 .tolist() 将 numpy 数组转换为列表,同时将类型更改为 Python 原生类型。例如:

>>> a = array([array([1.]), array([2, 3]), array(['a', 'b', 'c'])])
>>> a
array([array([ 1.]), array([2, 3]),
       array(['a', 'b', 'c'], 
      dtype='<U1')], dtype=object)
>>> t = tuple(tuple(x.tolist()) for x in a)
>>> t
((1.0,), (2, 3), ('a', 'b', 'c'))

我们在哪里

>>> [type(x[0]) for x in a]
[<class 'numpy.float64'>, <class 'numpy.int32'>, <class 'numpy.str_'>]

但现在有

>>> [type(x[0]) for x in t]
[<class 'float'>, <class 'int'>, <class 'str'>]

关于python - 在 Python 中将数组(numpy 数据类型)转换为元组( native 数据类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33724611/

相关文章:

python - gRPC/proto Google 云客户端库与 GAPIC Google 云客户端库

python - 导入错误 : No module named spiders

c++ - 为什么我需要两次使用这个语句 - 矩阵乘法

c++ - 可能具有长度为零的数组的模板化数据类型

python - 使用 poly1d polyder 求多项式的导数而不反转系数

python - 使用 NumPy 的 Mittag-Leffler 函数不稳定

python - 使用 multiprocessing.Pool 打开的文件太多

python - 如何从位于 Odoo 11 表单操作下拉列表中的按钮发送电子邮件?

c - 带有 struct 2d 数组的 strcmp

python - 对象成员的 Cython 缓冲区声明