Python 将元组列表转换为结构化的 numpy 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28176949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:52:07  来源:igfitidea点击:

Convert list of tuples to structured numpy array

pythonarraysnumpy

提问by aph

I have a list of Num_tuplestuples that all have the same length Dim_tuple

我有一个Num_tuples长度相同的元组列表Dim_tuple

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

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

为了确定性,让我们说Num_tuples=3Dim_tuple=2

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

I want to convert xlistinto a structured numpy array xarrusing a user-provided list of column names user_namesand a user-provided list of variable types user_types

我想使用用户提供的列名列表和用户提供的变量类型列表转换xlist为结构化的 numpy 数组xarruser_namesuser_types

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

So in the creation of the numpy array,

所以在创建 numpy 数组时,

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])

How can I slice xlistto create xarrwithout any loops?

如何xlistxarr没有任何循环的情况下切片创建?

采纳答案by hpaulj

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])

or if the names are important:

或者如果名称很重要:

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

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