Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.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 设置dtype时Numpy数组上的值重复_Python_Arrays_Python 3.x_Numpy - Fatal编程技术网

Python 设置dtype时Numpy数组上的值重复

Python 设置dtype时Numpy数组上的值重复,python,arrays,python-3.x,numpy,Python,Arrays,Python 3.x,Numpy,我有两个一维数组,为了方便起见,我们将其称为x和y: x = np.array([1., 3.]) y = np.array([2, 4]) 我想把它们连接成一个结构化数组。所需输出为: array([( 1., 2), ( 3., 4)], dtype=[('x', '<f8'), ('y', '<i8')]) 我得到以下信息: array([[( 1., 1), ( 2., 2)], [( 3., 3), ( 4., 4)]], dt

我有两个一维数组,为了方便起见,我们将其称为
x
y

x = np.array([1., 3.])
y = np.array([2, 4])
我想把它们连接成一个结构化数组。所需输出为:

array([( 1., 2), ( 3., 4)], 
      dtype=[('x', '<f8'), ('y', '<i8')])
我得到以下信息:

array([[( 1., 1), ( 2., 2)],
       [( 3., 3), ( 4., 4)]], 
      dtype=[('x', '<f8'), ('y', '<i8')])
数组([(1,1)、(2,2)],
[( 3., 3), ( 4., 4)]], 

dtype=[('x','您可以使用
np.rec.fromarrays

np.rec.fromarrays([x, y], dtype=[('x', '<f8'), ('y', '<i8')])
# rec.array([( 1., 2), ( 3., 4)], 
#           dtype=[('x', '<f8'), ('y', '<i8')])
np.rec.fromarrays([x,y],dtype=[('x',”不是完全重复的。这里是起点

[("Hello",2.5,3),("World",3.6,2)]
接受的解决方案使用
np.rec.fromArray
,但它必须转换输入。简短的解决方案使用
np.fromrecords

但是查看一下
fromArray
的代码,就可以找到一种简单的方法来实现这一点,特别是当您无法回忆起所有这些
重新排列
函数的隐藏位置时

In [200]: x = np.array([1., 3.])
     ...: y = np.array([2, 4])

In [201]: dt = [('x', '<f8'), ('y', '<i8')]

In [204]: arr = np.empty(x.shape[0], dtype=dt)
In [205]: for n, v in zip(arr.dtype.names, [x, y]):
     ...:     arr[n] = v

In [206]: arr
Out[206]: 
array([( 1., 2), ( 3., 4)], 
      dtype=[('x', '<f8'), ('y', '<i8')])
这是一个元组列表,因此我可以在结构化数组创建语句中直接使用它:

In [212]: np.array(_, dtype=dt)
Out[212]: 
array([( 1., 2), ( 3., 4)], 
      dtype=[('x', '<f8'), ('y', '<i8')])
[212]中的
:np.array(_,dtype=dt)
出[212]:
数组([(1,2)、(3,4)],
dtype=[('x','显示如何使用
fromrecords
构造
recarray
。但是使用
fromArray
可以更好地解决这个问题。
x
y
这里是字段,而不是记录。
In [210]: list(zip(*[x,y]))
Out[210]: [(1.0, 2), (3.0, 4)]
In [212]: np.array(_, dtype=dt)
Out[212]: 
array([( 1., 2), ( 3., 4)], 
      dtype=[('x', '<f8'), ('y', '<i8')])