如何将元组列表转换为 numpy 元组数组? [英] How convert a list of tupes to a numpy array of tuples?

查看:127
本文介绍了如何将元组列表转换为 numpy 元组数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的列表:

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

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

I want to convert it to a numpy array,and keep array item type as tuple:

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

但 numpy.array(l) 会给出:

but numpy.array(l) will give:

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

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

and item type has been changed from tuple to numpy.ndarray,then I specified item types

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

这给出:

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

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

but item type isn't tuple but numpy.void,so question is:

 how to convert it to a numpy.array of tuple,not of numpy.void? 

推荐答案

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

You can have an array of object dtype, letting each element of the array being a tuple, like so -

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

这篇关于如何将元组列表转换为 numpy 元组数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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