1

I would like to roll a 2D numpy array, each row being rolled by an amount defined in a 1D array. For example, I have

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

r=[1,2,2]

And I wish to perform the following task:

C=np.copy(A)
for i in range(3):
    C[i]=np.roll(C[i],r[i])
print(C)

[[3 1 2]
 [5 6 4]
 [8 9 7]]

Apparently, numpy roll function supports arrays as input. But the way it works is puzzling, and I don't get what I think I should get:

B=np.roll(A,r,1)
print(B)

[[2 3 1]
 [5 6 4]
 [8 9 7]]

Here, all the rows have been shifted by the same amount (which from my experiments seems to be the sum of the elements of my 1D array). What did I do wrong here? numpy.roll is much faster than a for loop, so I'd like to use it if possible, but I can't get it to output what I want.

1 Answers1

1

In numpy doc it explains:

shiftint or tuple of ints The number of places by which elements are shifted. If a tuple, then axis must be a tuple of the same size, and each of the given axes is shifted by the corresponding number. If an int while axis is a tuple of ints, then the same value is used for all given axes.

Which explains when you feed shift as tuple, you need to feed the axis a same sized tuple, and each dimension is rolled a constant number that is its corresponding value in the shift tuple.

For example, np.roll(A, (4,3), (1,2)) shifts the axis=1 4 steps and axis=2 3 steps.

To achieve your goal, please check this post for many sophisticated solutions.

Ehsan
  • 12,072
  • 2
  • 20
  • 33
  • Ah, I misunderstood what the numpy.roll function does, then. Thanks for the example, it made it clearer (it's a shame the numpy documentation doesn't have an example for the case of shifts in an array). And thank you for the link. I just thought numpy.roll did what is decribed there. – WINTERSDORFF Raphael Dec 09 '20 at 11:16