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

问题描述

我有一个Num_tuples元组的列表,它们都具有相同的长度Dim_tuple

I have a list of Num_tuples tuples that all have the same length Dim_tuple

xlist = [tuple_1, tuple_2, ..., tuple_Num_tuples]

为了明确起见,假设Num_tuples=3Dim_tuple=2

For definiteness, let's say Num_tuples=3 and Dim_tuple=2

xlist = [(1, 1.1), (2, 1.2), (3, 1.3)]

我想使用用户提供的列名user_names列表和用户提供的变量类型user_types

I want to convert xlist into a structured numpy array xarr using a user-provided list of column names user_names and a user-provided list of variable types user_types

user_names = [name_1, name_2, ..., name_Dim_tuple]
user_types = [type_1, type_2, ..., type_Dim_tuple]

因此在创建numpy数组时,

So in the creation of the numpy array,

dtype = [(name_1,type_1), (name_2,type_2), ..., (name_Dim_tuple, type_Dim_tuple)]

在我的玩具示例中,所需的最终产品看起来像这样:

In the case of my toy example desired end product would look something like:

xarr['name1']=np.array([1,2,3])
xarr['name2']=np.array([1.1,1.2,1.3])

我如何切片xlist来创建xarr而没有任何循环?

How can I slice xlist to create xarr without any loops?

推荐答案

元组列表是向结构化数组提供数据的正确方法:

A list of tuples is the correct way of providing data to a structured array:

In [273]: xlist = [(1, 1.1), (2, 1.2), (3, 1.3)]

In [274]: dt=np.dtype('int,float')

In [275]: np.array(xlist,dtype=dt)
Out[275]:
array([(1, 1.1), (2, 1.2), (3, 1.3)],
      dtype=[('f0', '<i4'), ('f1', '<f8')])

In [276]: xarr = np.array(xlist,dtype=dt)

In [277]: xarr['f0']
Out[277]: array([1, 2, 3])

In [278]: xarr['f1']
Out[278]: array([ 1.1,  1.2,  1.3])

或者名称是否重要:

In [280]: xarr.dtype.names=['name1','name2']

In [281]: xarr
Out[281]:
array([(1, 1.1), (2, 1.2), (3, 1.3)],
      dtype=[('name1', '<i4'), ('name2', '<f8')])

http://docs.scipy. org/doc/numpy/user/basics.rec.html#filling-structured-arrays

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

08-01 14:31