这将是一个
vectorized
方法,假设
A
作为输入阵列-
# Get shape info and the middle column index
M,N = A.shape
mid_col_idx = int(N/2)
# Get required shifts for each row
shifts = mid_col_idx - np.argmax(A,axis=1)
# Get offsetted column indices
offsetted_col_idx = np.mod(np.arange(N) - shifts[:,None],N)
# Finally generate correctly ordered linear indices for all elements
# and set them in A in one-go
Aout = A.ravel()[offsetted_col_idx + N*np.arange(M)[:,None]]
样品运行-
In [74]: A
Out[74]:
array([[ 1, 3, 4, 10, 2, 4, 1],
[ 2, 4, 10, 1, 1, 1, 2],
[ 1, 4, 7, 5, 4, 10, 1]])
In [75]: Aout
Out[75]:
array([[ 1, 3, 4, 10, 2, 4, 1],
[ 2, 2, 4, 10, 1, 1, 1],
[ 7, 5, 4, 10, 1, 1, 4]])