如何将元组列表转换为 numpy 元组数组?

问题描述 投票:0回答:4

我有一个这样的清单:

l=[(1,2),(3,4)]

我想将其转换为 numpy 数组,并将数组项类型保留为元组:

array([(1,2),(3,4)])

但是 numpy.array(l) 会给出:

array([[1,2],[3,4)]])

并且项目类型已从 tuple 更改为 numpy.ndarray,然后我指定了项目类型

numpy.array(l,numpy.dtype('float,float'))

这给出了:

 array([(1,2),(3,4)])

但是项目类型不是元组而是 numpy.void,所以问题是:

 how to convert it to a numpy.array of tuple,not of numpy.void? 
python numpy numpy-ndarray
4个回答
27
投票

你可以有一个

object
dtype 的数组,让数组的每个元素都是一个元组,就像这样 -

out = np.empty(len(l), dtype=object)
out[:] = l

样品运行 -

In [163]: l = [(1,2),(3,4)]

In [164]: out = np.empty(len(l), dtype=object)

In [165]: out[:] = l

In [172]: out
Out[172]: array([(1, 2), (3, 4)], dtype=object)

In [173]: out[0]
Out[173]: (1, 2)

In [174]: type(out[0])
Out[174]: tuple

8
投票

出于某种原因,如果你正在寻找一行代码,你不能简单地这样做(尽管 Divakar 的答案最终给你留下了

dtype=object
):

np.array([(1,2),(3,4)], dtype=object)

相反,你必须这样做:

np.array([(1,2),(3,4)], dtype="f,f")

"f,f"
向数组发出信号,表示它正在接收两个浮点数的元组(或者您可以使用
"i,i"
表示整数)。如果需要,您可以通过在上面的行末尾添加
.astype(object)
来转换回对象)。


0
投票

刚刚发现 pandas 有办法解决这个问题。 您可以使用他们的

MultiIndex
类来创建元组数组 因为所有 pandas 索引都是包装的一维 numpy 数组。 就像在元组列表上调用
Index
构造函数一样简单。

>>> import pandas as pd
>>> tups = [(1, 2), (1, 3)]
>>> tup_array = pd.Index(tups).values
>>> print(type(tup_array), tup_array)
<class 'numpy.ndarray'> [(1, 2) (1, 3)]

0
投票
>>> np.fromiter(l, object)
array([(1, 2), (3, 4)], dtype=object)
从 NumPy 1.23 开始,

np.fromiter
支持
object
dtype。 https://numpy.org/doc/stable/reference/ generated/numpy.fromiter.html

© www.soinside.com 2019 - 2024. All rights reserved.