Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming slices of numpy arrays in Python

Tags:

python

numpy

I have a large matrix that represents.. say 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 have sliced it into parts that represent the faces.

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 now assign a modified matrix to the left face.

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

But this does not change the values in the parent matrix cube. I understand this is because the newly generated matrix is being assigned to the variable left_f and so the reference 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 wouldn't be very readable. How do I assign a new matrix to a named slice of another matrix in a pythonic way?

like image 627
Harsh Avatar asked Oct 29 '22 10:10

Harsh


1 Answers

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)
like image 83
Tristan Avatar answered Nov 15 '22 05:11

Tristan