如何使用附加属性扩展我的 2dim numpy 数组

Max*_*Max 3 python numpy

我有一个 2 暗的 numpy 数组,从一个起点到每个端点的距离,我想对距离进行排序,但要做到这一点,我必须给距离一个索引,这样我就不会失去对端点的引用。

如何添加索引?最好没有循环

我已经使用numpy.expand_dims将数组扩展了 1 dim,但我不知道如何附加索引。

所以我目前的做法是:

indexArray = [1,2,3]
distances = np.array([[0.3, 0.5, 0.2], [0.7, 0.1, 0.5], [0.2, 0.3, 0.8]])
distances = np.expand_dims(distances, axis=2)
Run Code Online (Sandbox Code Playgroud)

现在距离看起来像:

[[[0.3], [0.5], [0.2]], 
 [[0.7], [0.1], [0.5]],
 [[0.2], [0.3], [0.8]]]
Run Code Online (Sandbox Code Playgroud)

现在我想附加 indexArray 使距离数组看起来像:

[[[1, 0.3], [2, 0.5], [3, 0.2]],
 [[1, 0.7], [2, 0.1], [3, 0.5]],
 [[1, 0.2], [2, 0.3], [3, 0.8]]]
Run Code Online (Sandbox Code Playgroud)

use*_*203 5

您可以在这里使用切片分配,不需要expand_dims, 广播将负责其余部分。


out = np.empty(distances.shape + (2,))
out[..., 0] = indexArray
out[..., 1] = distances
Run Code Online (Sandbox Code Playgroud)

array([[[1. , 0.3],   
        [2. , 0.5],   
        [3. , 0.2]],  

       [[1. , 0.7],   
        [2. , 0.1],   
        [3. , 0.5]],  

       [[1. , 0.2],   
        [2. , 0.3],   
        [3. , 0.8]]])
Run Code Online (Sandbox Code Playgroud)