Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将元组列表转换为结构化numpy数组_Python_Arrays_Numpy - Fatal编程技术网

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

Python 将元组列表转换为结构化numpy数组,python,arrays,numpy,Python,Arrays,Numpy,我有一个Num\u元组的列表,所有元组的长度都相同Dim\u元组 xlist = [tuple_1, tuple_2, ..., tuple_Num_tuples] 为了明确起见,我们假设Num\u tuple=3和Dim\u tuple=2 xlist = [(1, 1.1), (2, 1.2), (3, 1.3)] 我想使用用户提供的列名列表和变量类型列表将xlist转换为结构化numpy数组xarr user_names = [name_1, name_2, ..., name_Dim

我有一个
Num\u元组的列表,所有元组的长度都相同
Dim\u元组

xlist = [tuple_1, tuple_2, ..., tuple_Num_tuples]
为了明确起见,我们假设
Num\u tuple=3
Dim\u tuple=2

xlist = [(1, 1.1), (2, 1.2), (3, 1.3)]
我想使用用户提供的列名列表和变量类型列表将
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])
[273]中的
xlist=[(1,1.1)、(2,1.2)、(3,1.3)]
在[274]中:dt=np.dtype('int,float')
[275]中的np.数组(xlist,dtype=dt)
出[275]:
数组([(1,1.1)、(2,1.2)、(3,1.3)],

dtype=[('f0','
没有任何循环
没有循环这可能吗?关于列表理解呢?还有,你尝试过什么吗?是的,尽管我唯一要做的是首先涉及xlist-->np.array(xlist)的硬编码解决方案。例如,xtemp=np.array(xlist)和x1=np.array(xtemp[:,1]),这创建了一个由一个元素元组组成的numpy数组,这不是我想要的。我似乎无法正确地进行切片,这就是整个问题。我意识到,应该很简单。这让我找到了我的起点。
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')])