3
votes

I have a 2 dim numpy array with distances from one startpoint to each endpoint and i want to sort the distances, but to do that i have to give the distances an index so i don't loose the refernce to the endpoint.

How can i add the index? Best without loops

I have already expanded the array by 1 dim using numpy.expand_dims but i don't know how to append the indices.

So my current approach is:

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)

now distances looks like:

[[[0.3], [0.5], [0.2]], 
 [[0.7], [0.1], [0.5]],
 [[0.2], [0.3], [0.8]]]

and now I want to append the indexArray so the distance array looks like:

[[[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]]]
2

2 Answers

5
votes

You could just use sliced assignment here, no need for the expand_dims, broadcasting will take care of the rest.


out = np.empty(distances.shape + (2,))
out[..., 0] = indexArray
out[..., 1] = distances

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]]])
0
votes

There are many ways to interleave two arrays. The only difference here is that indexArray needs to be broadcasted first.

indexArray = np.array([1,2,3])
distances = np.array([[0.3, 0.5, 0.2], [0.7, 0.1, 0.5], [0.2, 0.3, 0.8]])

indexArray = np.broadcast_to(indexArray, distances.shape)

# do the interleave
np.dstack((indexArray.T, distances))

Output:

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

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

       [[3. , 0.2],
        [3. , 0.3],
        [3. , 0.8]]])

If you want the same output as the other post by user3483203, then don't transpose indexArray.