Naming slices of numpy arrays in Python

I have a large matrix, which is a Rubik's Cube.

>>cube

>>[[-1, -1, -1,  1,  2,  3, -1, -1, -1, -1, -1, -1],
   [-1, -1, -1,  4,  5,  6, -1, -1, -1, -1, -1, -1],
   [-1, -1, -1,  7,  8,  9, -1, -1, -1, -1, -1, -1],
   [ 1,  2,  3,  4,  5,  6,  7,  8,  9,  8,  1,  8],
   [ 4,  5,  6,  0,  7,  7,  6,  9,  6,  8,  1,  0],
   [ 7,  8,  9,  6,  9,  7,  6,  6,  9,  0,  1,  7],
   [-1, -1, -1,  1,  1,  0, -1, -1, -1, -1, -1, -1],
   [-1, -1, -1,  8,  8,  1, -1, -1, -1, -1, -1, -1],
   [-1, -1, -1,  8,  0,  1, -1, -1, -1, -1, -1, -1],
   [-1, -1, -1,  7,  1,  0, -1, -1, -1, -1, -1, -1],
   [-1, -1, -1,  0,  1,  8, -1, -1, -1, -1, -1, -1],
   [-1, -1, -1,  8,  1,  8, -1, -1, -1, -1, -1, -1]])

I cut it into pieces representing the edges.

top_f   = cube[0:3,3:6]
botm_f  = cube[6:9,3:6]

back_f  = cube[3:6,9:12]
front_f = cube[3:6,3:6]
left_f  = cube[3:6,0:3]
right_f = cube[3:6,6:9]

I want to assign a modified matrix to the left side.

left_f = numpyp.rot90(left_f, k=3)

But this does not change the value in the parent matrix cube. I understand this because the newly created matrix is ​​assigned to the variable left_f, and therefore the link to the sub-slice cube[3:6,0:3]is lost.

I could just resort to replacing it directly.

cube[3:6,0:3] = numpyp.rot90(left_f, k=3)

But that would not be very readable. How to assign a new matrix to a named slice of another matrix in a pythonic way?

+4
source share
1 answer

You can assign your slices to a variable:

left_face = slice(3, 6), slice(0, 3)
cube[left_face] = np.rot90(cube[left_face], k=3)
+1
source

Source: https://habr.com/ru/post/1672051/


All Articles