Efficient way to shift 2D-matrixes in python in both directions
Question: Given a two dimensional matrix, e.g.

    
    
    l = [[1,1,1],
         [2,5,2],
         [3,3,3]])
    

what is the most efficient way of implementing a shift operation on columns
and rows?

E.g.

    
    
    shift('up', l) 
    
    [[2, 5, 2],
     [3, 3, 3],
     [1, 1, 1]]
    

but

    
    
    shift('left', l) 
    
    [[1, 1, 1],
     [5, 2, 2],
     [3, 3, 3]]
    

I'm using `collections.deque` on both depths because of [this
answer](http://stackoverflow.com/a/2150125/931303) but while a 'up' or 'down'
only requires 1 shift, a 'left' or 'right' requires N shifts (my
implementation is using a for cycle for each row).

In C I think this can be improved using pointer arithmetic (see e.g. [this
answer](http://stackoverflow.com/a/1479089/931303)).

Is there a better pythonic way?

**EDIT:**

  * By efficient I mean if there is a way of avoiding the N shifts.
  * We can assume the matrix is squared.
  * The shift can be in place.

Thanks to martineau for pointing out these important points of the question.
I'm sorry I didn't pointed them out before.


Answer: Numpy provides a method called roll() to shift entries.

    
    
    >>> import numpy as np
    >>> x = np.arange(9)
    >>> x = x.reshape(3, 3)
    >>> print(x)
    
    [[0 1 2]
     [3 4 5]
     [6 7 8]]
    
    >>> x = np.roll(x, -1, axis=0) # up
    >>> print(x)
    
    [[3 4 5]
     [6 7 8]
     [0 1 2]]
    
    >>> x = np.roll(x, 1, axis=0) # down
    >>> print(x)
    
    [[0 1 2]
     [3 4 5]
     [6 7 8]]
    
    >>> x = np.roll(x, 2, axis=1) # right
    >>> print(x)
    
    [[1 2 0]
     [4 5 3]
     [7 8 6]]
    
    >>> x = np.roll(x, -2, axis=1) # left
    >>> print(x)    
    
    [[0 1 2]
     [3 4 5]
     [6 7 8]]
    

I guess that [Numpy](http://en.wikipedia.org/wiki/NumPy) will be pretty
efficient compared to most solutions  
in terms of matrix operations and you won't be bound to a 2 dimensional
matrix.

