Rotate numpy 2D array
See the comment of cgohlke Nov 10 '11 at 18:34:
Consider scipy.ndimage.interpolation.shift() and rotate() for interpolated translations and rotations of 2D numpy arrays.
The basic operations are described in the Wikipedia transformation matrix page - I'm not going to try to do ascii matrix art here, but the output P' = R*P where P' is the output point, R is the 2x2 transformation matrix containing sine and cosine of the rotation angle, and P is the input point. If you want to rotate about something other than the origin, then shift the the origin prior to rotation: P' = T + R*(P-T) where T is the translation coordinate. The basic matrix operations don't do interpolation, so if you aren't using a numpy-based image processing library, you'll want to do a reverse transform: for each (integer-valued) output coordinate, find the (floating point) coordinate of the point that would be rotated into it, and interpolate the value of that input point from the surrounding pixels.
I would like take help of above and solve this by an example:
import pandas as pdimport numpy as npbd = np.matrix([[44., -1., 40., 42., 40., 39., 37., 36., -1.], [42., -1., 43., 42., 39., 39., 41., 40., 36.], [37., 37., 37., 35., 38., 37., 37., 33., 34.], [35., 38., -1., 35., 37., 36., 36., 35., -1.], [36., 35., 36., 35., 34., 33., 32., 29., 28.], [38., 37., 35., -1., 30., -1., 29., 30., 32.]])def rotate45(array): rot = [] for i in range(len(array)): rot.append([0] * (len(array)+len(array[0])-1)) for j in range(len(array[i])): rot[i][int(i + j)] = array[i][j] return rotdf_bd = pd.DataFrame(data=np.matrix(rotate45(bd.transpose().tolist())))df_bd = df_bd.transpose()print df_bd
of which output will be like:
44 0 0 0 0 0 0 0 042 -1 0 0 0 0 0 0 037 -1 40 0 0 0 0 0 035 37 43 42 0 0 0 0 036 38 37 42 40 0 0 0 038 35 -1 35 39 39 0 0 00 37 36 35 38 39 37 0 00 0 35 35 37 37 41 36 00 0 0 -1 34 36 37 40 -10 0 0 0 30 33 36 33 360 0 0 0 0 -1 32 35 340 0 0 0 0 0 29 29 -10 0 0 0 0 0 0 30 280 0 0 0 0 0 0 0 32