将两个2D numpy数组连接成一个2元组的2D数组

时间:2021-02-02 12:13:04

I have two 2D numpy arrays like this, representing the x/y distances between three points. I need the x/y distances as tuples in a single array.

我有两个像这样的2D numpy数组,代表三点之间的x / y距离。我需要将x / y距离作为单个数组中的元组。

So from:

所以来自:

x_dists = array([[ 0, -1, -2],
                 [ 1,  0, -1],
                 [ 2,  1,  0]])

y_dists = array([[ 0, -1, -2],
                 [ 1,  0, -1],
                 [ 2,  1,  0]])

I need:

我需要:

dists = array([[[ 0,  0], [-1, -1], [-2, -2]],
               [[ 1,  1], [ 0,  0], [-1, -1]],
               [[ 2,  2], [ 1,  1], [ 0,  0]]])

I've tried using various permutations of dstack/hstack/vstack/concatenate, but none of them seem to do what I want. The actual arrays in code are liable to be gigantic, so iterating over the elements in python and doing the rearrangement "manually" isn't an option speed-wise.

我已经尝试过使用dstack / hstack / vstack / concatenate的各种排列,但它们似乎都没有做我想要的。代码中的实际数组可能是巨大的,因此迭代python中的元素并“手动”进行重新排列不是速度方面的选择。

Edit: This is what I came up with in the end: https://gist.github.com/807656

编辑:这是我最终提出的:https://gist.github.com/807656

2 个解决方案

#1


10  

import numpy as np
dists = np.vstack(([x_dists.T], [y_dists.T])).T

returns dists like you wanted them. Afterwards it is not "a single 2D array of 2-tuples", but a normal 3D array where the third axis is the concatenation of the two original arrays.

像你想要的那样返回dists。之后,它不是“单个2元组的二维阵列”,而是一个普通的3D阵列,其中第三个轴是两个原始阵列的串联。

You see:

你看:

dists.shape # (3, 3, 2)

#2


7  

numpy.rec.fromarrays([x_dists, y_dists], names='x,y')

#1


10  

import numpy as np
dists = np.vstack(([x_dists.T], [y_dists.T])).T

returns dists like you wanted them. Afterwards it is not "a single 2D array of 2-tuples", but a normal 3D array where the third axis is the concatenation of the two original arrays.

像你想要的那样返回dists。之后,它不是“单个2元组的二维阵列”,而是一个普通的3D阵列,其中第三个轴是两个原始阵列的串联。

You see:

你看:

dists.shape # (3, 3, 2)

#2


7  

numpy.rec.fromarrays([x_dists, y_dists], names='x,y')