1

I have a large matrix where I want to permute (or shift) one row of it.
For example:

np.array([[1, 2, 3, 4],
          [1, 2, 3, 4],
          [1, 2, 3, 4],
          [1, 2, 3, 4]])

And the desired shifting output is: (for the second row by 1, for that example)

np.array([[1, 2, 3, 4],
          [2, 3, 4, 1],
          [1, 2, 3, 4],
          [1, 2, 3, 4]])

This can be done naively by extracting the row of interest, permute and stick it back in the matrix. I want a better solution that is in-place and efficient.

  1. How to shift desired row or column by n places?
  2. How to permute (change the order as desired)?
  3. Can this be done efficiently for more than 1 row? for example shift the i'th row i places forward:
np.array([[1, 2, 3, 4],
          [2, 3, 4, 1],
          [3, 4, 1, 2],
          [4, 1, 2, 3]])
GalSuchetzky
  • 785
  • 5
  • 21
  • Does this answer your question? https://stackoverflow.com/questions/20360675/roll-rows-of-a-matrix-independently – yatu Sep 22 '20 at 10:10

1 Answers1

0

You can do it indexing by slicing the rows and rolling them:

import numpy as np

a = np.array([[1, 2, 3, 4],
              [1, 2, 3, 4],
              [1, 2, 3, 4],
              [1, 2, 3, 4]])

shift = 2
rows = [1, 3]
a[rows] = np.roll(a[rows], shift, axis=1)

array([[1, 2, 3, 4], [3, 4, 1, 2], [1, 2, 3, 4], [3, 4, 1, 2]])

dzang
  • 2,160
  • 2
  • 12
  • 21