Home > Back-end >  Rearranging numpy arrays
Rearranging numpy arrays

Time:01-27

I was not able to find a duplicate of my question, unfortunately, although I am sure that this is a problem which has been solved before

I have a numpy array with a certain set of indices, eg.

ind1 = np.array([1, 3, 5, 7])

With these indices, I can filter some values from another array. Lets call this other array rows. As an example, I can retrieve

rows[ind1] = [1, 10, 20, 15]

The order of rows[ind1] must not be changed in the following.

I have another index array, ind2

ind2 = np.array([4, 5, 6, 7])

I also have an array cols, where I can filter values from using ind2. I know that cols[ind2] results in an array which has the size of rows[ind1] and the entries are the same, but the order is different. An example:

cols[ind2] = [15, 20, 10, 1]

I would like to rearrange the order of cols[ind2], so that it corresponds to rows[ind1]. I am interested in the corresponding order of ind2.

In the example, the result should be

cols[ind2] = [1, 10, 20, 15] ind2 = [7, 6, 5, 4]

Using numpy, I did not find a way to do this. Any ideas would be helpful. Thanks in advance.

CodePudding user response:

There may be a better way, but you can do this using argsorts.

Let's call your "reordered ind2" ind3.

If you are sure that rows[ind1] and cols[ind2] will have the same length and all of the same elements, then the sorted versions of both will be the same i.e np.sort(rows[ind1]) = np.sort(cols[ind2]).

If this is the case, and you don't run into any problems with repeated elements (unsure of your exact use case), then what you can do is find the indices to put cols[ind2] in order, and then from there, find the indices to put np.sort(cols[ind2]) into the order of rows[ind1].

So, if

p1 = np.argsort(rows[ind1])

and

p2 = np.argsort(cols[ind2])

and

p3 = np.argsort(p1)

Then ind3 = ind2[p2][p3]. The reason this works is because if you do an argsort of an argsort, it gives you the indices you need to reverse the first sort. p2 sorts cols[ind2] (that's the definition of argsort), and p3 unsorts the result of that back into the order of rows[ind1].

CodePudding user response:

Seemed to work so far. Thanks!

  •  Tags:  
  • Related