[英]Convert list of tuples to structured numpy array
我有一个Num_tuples
元组的列表,它们都具有相同的长度Dim_tuple
xlist = [tuple_1, tuple_2, ..., tuple_Num_tuples]
为了确定性,假设Num_tuples=3
和Dim_tuple=2
xlist = [(1, 1.1), (2, 1.2), (3, 1.3)]
我想使用用户提供的列名user_names
列表和用户提供的变量类型列表user_types
将xlist
转换为结构化的 numpy 数组xarr
user_names = [name_1, name_2, ..., name_Dim_tuple]
user_types = [type_1, type_2, ..., type_Dim_tuple]
所以在创建 numpy 数组时,
dtype = [(name_1,type_1), (name_2,type_2), ..., (name_Dim_tuple, type_Dim_tuple)]
在我的玩具示例中,所需的最终产品如下所示:
xarr['name1']=np.array([1,2,3])
xarr['name2']=np.array([1.1,1.2,1.3])
如何在没有任何循环的情况下切片xlist
以创建xarr
?
元组列表是向结构化数组提供数据的正确方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.