我有一个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)]
我想使用用户提供的列名列表和用户提供的变量类型列表转换xlist
为结构化的numpy数组xarr
user_names
user_types
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句