I know that you can move an array with NumPy so if you use np.roll you can shift array to right or to the left. I was wondering how to move a specific set of values with in the array to either left right up or down.
if I wanted to move what is circled in red to the left how would i be able to move that and nothing else?
Advertisement
Answer
numpy
can use slice
to get subarray and later assing it in different place
import numpy as np x = [ [0, 1, 2, 1, 0, 0, 1, 2, 1, 0 ], [0, 1, 2, 1, 0, 0, 1, 2, 1, 0 ] ] arr = np.array(x) print(arr) subarr = arr[0:2,1:4] # get values print(subarr) arr[0:2,0:3] = subarr # put in new place print(arr)
Result:
[[0 1 2 1 0 0 1 2 1 0] [0 1 2 1 0 0 1 2 1 0]] [[1 2 1] [1 2 1]] [[1 2 1 1 0 0 1 2 1 0] [1 2 1 1 0 0 1 2 1 0]]
It keeps original values in [0][1]
, [1][1]
. If you want remove them then you could copy subarray, set zero
in original place, and put copy in new place
import numpy as np x = [ [0, 1, 2, 1, 0, 0, 1, 2, 1, 0 ], [0, 1, 2, 1, 0, 0, 1, 2, 1, 0 ] ] arr = np.array(x) print(arr) subarr = arr[0:2,1:4].copy() # duplicate values print(subarr) arr[0:2,1:4] = 0 # remove original values arr[0:2,0:3] = subarr # put in new place print(arr)
Result
[[0 1 2 1 0 0 1 2 1 0] [0 1 2 1 0 0 1 2 1 0]] [[1 2 1] [1 2 1]] [[1 2 1 0 0 0 1 2 1 0] [1 2 1 0 0 0 1 2 1 0]]