如何在Python中移动2D numpy数组的元素?
例如,转换此数组:
[[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]]
此数组:
[[0, 0, 0,],
[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9]]
答案 0 :(得分:1)
我要手动进行切片,这是切片的工作方式:
import numpy as np
A = np.array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])
A[1:,:] = A[:3,:]
A[:1,:] = [0, 0, 0]
答案 1 :(得分:1)
import numpy as np
a = np.array([[ 1, 2, 3],
[ 4, 5, 6],
[ 7, 8, 9],
[10, 11, 12]])
def shift_array(array, place):
new_arr = np.roll(array, place, axis=0)
new_arr[:place] = np.zeros((new_arr[:place].shape))
return new_arr
shift_array(a,2)
# array([[ 0, 0, 0],
# [ 0, 0, 0],
# [ 1, 2, 3],
# [ 4, 5, 6]])