Home > Back-end >  Reorganizing array elements in Python
Reorganizing array elements in Python

Time:06-26

How do I reorganize elements of A (shape = (1,7,2)) to generate new array A1 (shape = (1,7,2)) in order of increasing j? In A[0,0]= array([0, 1]), j refers to 1 in [0,1].

It would be great to have something very generic so that the code can deal with when shape of A becomes very large, say (1,1000,2).

import numpy as np

A = np.array([[[0, 1],[0, 2],[1, 3],[2, 5],[3, 4],[4, 7],[5, 6]]])
print("A =", A.shape)

The desired output is

A1 = np.array([[[0, 1],[0, 2],[1, 3],[3, 4],[2, 5],[5, 6],[4, 7]]])

CodePudding user response:

The order is defined first, then the array is sorted by order.

A = np.array([[[0, 1],[0, 2],[1, 3],[2, 5],[3, 4],[4, 7],[5, 6]]])
order = A[0,:, 1].argsort()
A =np.array([A[0][order]])
print(A)
  • Related