aph*_*aph 15 python arrays numpy
我有一个Num_tuples元组列表,它们都具有相同的长度Dim_tuple
xlist = [tuple_1, tuple_2, ..., tuple_Num_tuples]
Run Code Online (Sandbox Code Playgroud)
确切地说,让我们说Num_tuples = 3和Dim_tuple = 2
xlist = [(1, 1.1), (2, 1.2), (3, 1.3)]
Run Code Online (Sandbox Code Playgroud)
我想使用用户提供的列名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]
Run Code Online (Sandbox Code Playgroud)
所以在创建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])
Run Code Online (Sandbox Code Playgroud)
如何切片xlist创建没有任何循环的xarr?
hpa*_*ulj 27
元组列表是向结构化数组提供数据的正确方法:
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])
Run Code Online (Sandbox Code Playgroud)
或者如果名称很重要:
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')])
Run Code Online (Sandbox Code Playgroud)
http://docs.scipy.org/doc/numpy/user/basics.rec.html#filling-structured-arrays