7

Not sure how to best title this question, but basically I would like to generate a new numpy array to be based on an existing array. The only difference is that the values have been shifted to an index I specify. Also assume that wrapping is required.

For simplicity, consider the base array:

[[0,1,2],
 [3,4,5],
 [6,7,8]]

If I want the zero (0) or the first element from the base array to be shifted at (0,1), it will be:

[[2,0,1],
 [5,3,4],
 [8,6,7]]

If I want the first element moved at (2,2) it will be:

[[4,5,3],
 [7,8,6],
 [1,2,0]]
3
  • I assume the 5 in matrix_2 position [2, 0] should be an 8. Can't edit because the edit is "too short" per SO requirements. Commented Nov 26, 2018 at 6:37
  • Yes, sorry typo. I updated the question. Thanks Commented Nov 26, 2018 at 6:39
  • Depending on how often you do this, you might want to consider a ring buffer instead. The answer recommending np.roll is O(n). Commented Nov 26, 2018 at 6:47

1 Answer 1

11

Use numpy.roll. For instance, for the first output you can roll 1 index to the right, meaning along axis 1:

import numpy as np
x = np.array([[0,1,2], [3,4,5], [6,7,8]])
x_shifted = np.roll(x, shift=1, axis=1)

Due to commutativity you can roll twice (once along each dimension) for the two-directional cyclic permutation effect:

x_double_shifted = np.roll(np.roll(x, shift=2, axis=1), shift=2, axis=0)

Obviously can be done more "pretty" ;-)
Good luck!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.