如何有效地转换 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/