0

I have a matrix A whose rows have to be reordered or shuffled according to the sequence in array b. The actual size of a Matrix A is more than 100 rows. The suggested answer need to be scalable.

A = np.array([[1,2,3],[4,5,6],[7,8,9]])
b = np.array([3,1,2])

Desired Output:

A = np.array([[7,8,9],[1,2,3],[4,5,6]])
2
  • A = A[b-1,...] that's it. This is called 'broadcasting' arrays. Also keep in mind that arrays in python indexed from 0 (not from 1!), thus we substract -1 from b. Commented Jun 5, 2024 at 15:58
  • No, it's 1D array.
    – M.Patil
    Commented Jun 6, 2024 at 5:22

1 Answer 1

0

It is based on Indexing the Matrix. Since row wise sorting is expected, the first bracket will contain the indexing array. Here is the catch, that python numbering begins with zero. Hence, instead of using b as index, (b-1) is used as index. By this way, the expected result is obtained.

A=A[b-1][:]
1
  • As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Commented Jun 6, 2024 at 6:03

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.