## How do you rotate elements in a 2D numpy array by 'n' units?

Question

```
x = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
```

Rotation by 1 unit should give:

```
x = [[4, 1, 2],
[7, 5, 3],
[8, 9, 6]]
```

Basically, I want to shift each circular layer in the array by 'n' units.

I looked at numpy.roll but couldn't figure out to use it for this use case. I cannot use image rotation routines like scipy.ndimage.interpolation.rotate as they change the shape and not quite achieve the desired result.

**Edit:**

For the 4 X 4 matrix:

```
x = [[a, b, c, d],
[e, f, g, h],
[i, j, k, l],
[m, n, o, p]]
```

Rotation by 1 unit should give:

```
x = [[e, a, b, c],
[i, j, f, d],
[m, k, g, h],
[n, o, p, l]]
```

**Edit:**

Adding some clarifications on how this works for arbitrary sizes.

For a N X N matrix rotated by 1 unit, the outer 'ring' is first shifted by 1. Same logic is followed the remaining 'inner' (N-2) X (N-2) matrix recursively.

Show source

## Answers to How do you rotate elements in a 2D numpy array by 'n' units? ( 3 )

For a 3x3 array, you can accomplish this with

`np.roll`

and`ndarray.flat`

:Rotate by 1 unit:

Rotate by 4 units:

For the 4x4 case, I still need some clarity on whether each "circle" needs to be rotated at different "speeds" according to their length...

Here's an approach assuming you are looking to rotate such that the amount of shift is constant across slices, where by slice we mean the outermost layer of elements directed outwards from the center -

Sample runsCase #1 (3 x 3 array) :

Case #2 (4 x 4 array) :

You're applying a permutation on the matrix. Permutations are usually represented by vectors, (i-->p[i]), and applied on vectors. You can represent a permutation of a matrix in a matrix if you want, the permutation will be a matrix of pairs, so that the element at (i,j) moves to m[i,j] .

Once you build the matrix, it's just a matter of a simple loop to apply the permutation.