Reputation: 2913
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]]
Upvotes: 7
Views: 2322
Reputation: 2895
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!
Upvotes: 11