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
JavaScript
x
18
18
1
import numpy as np
2
3
x = [
4
[0, 1, 2, 1, 0, 0, 1, 2, 1, 0 ],
5
[0, 1, 2, 1, 0, 0, 1, 2, 1, 0 ]
6
]
7
8
arr = np.array(x)
9
10
print(arr)
11
12
subarr = arr[0:2,1:4] # get values
13
print(subarr)
14
15
arr[0:2,0:3] = subarr # put in new place
16
17
print(arr)
18
Result:
JavaScript
1
9
1
[[0 1 2 1 0 0 1 2 1 0]
2
[0 1 2 1 0 0 1 2 1 0]]
3
4
[[1 2 1]
5
[1 2 1]]
6
7
[[1 2 1 1 0 0 1 2 1 0]
8
[1 2 1 1 0 0 1 2 1 0]]
9
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
JavaScript
1
20
20
1
import numpy as np
2
3
x = [
4
[0, 1, 2, 1, 0, 0, 1, 2, 1, 0 ],
5
[0, 1, 2, 1, 0, 0, 1, 2, 1, 0 ]
6
]
7
8
arr = np.array(x)
9
10
print(arr)
11
12
subarr = arr[0:2,1:4].copy() # duplicate values
13
print(subarr)
14
15
arr[0:2,1:4] = 0 # remove original values
16
17
arr[0:2,0:3] = subarr # put in new place
18
19
print(arr)
20
Result
JavaScript
1
9
1
[[0 1 2 1 0 0 1 2 1 0]
2
[0 1 2 1 0 0 1 2 1 0]]
3
4
[[1 2 1]
5
[1 2 1]]
6
7
[[1 2 1 0 0 0 1 2 1 0]
8
[1 2 1 0 0 0 1 2 1 0]]
9