移动矩阵行以在中间有最大值
Shift matrix rows to have maxima in the middle
这可以通过 for 循环和条件来实现,但是有没有一种快速有效的方法可以使用 Python 和 numpy 来实现,因为我正在处理具有数十万行的矩阵。
例如,我们有一个 3 行的小矩阵
1, 3, 4, 10, 2, 4, 1
2, 4, 10, 1, 1, 1, 2
1, 4, 7, 5, 4, 10, 1
因此,我希望循环移动行,使每行的最大值位于中间
1, 3, 4, 10, 2, 4, 1
2, 2, 4, 10, 1, 1, 1
7, 5, 4, 10, 1, 1, 4
我当时的想法是这样的:
middle = matrix.shape[1]/2
for row in range(0, matrix.shape[0]):
max_index = np.argmax(matrix[row, :])
np.roll(matrix[row, :], middle-max_index)
我认为 argmax 可以提取所有行的所有最大值索引。但是如何对每一行应用不同的移位,np.roll 没有提供这样的功能,因为移位必须是一个 int 而不是一个数组。
这将是一种 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]])
这可以通过 for 循环和条件来实现,但是有没有一种快速有效的方法可以使用 Python 和 numpy 来实现,因为我正在处理具有数十万行的矩阵。
例如,我们有一个 3 行的小矩阵
1, 3, 4, 10, 2, 4, 1
2, 4, 10, 1, 1, 1, 2
1, 4, 7, 5, 4, 10, 1
因此,我希望循环移动行,使每行的最大值位于中间
1, 3, 4, 10, 2, 4, 1
2, 2, 4, 10, 1, 1, 1
7, 5, 4, 10, 1, 1, 4
我当时的想法是这样的:
middle = matrix.shape[1]/2
for row in range(0, matrix.shape[0]):
max_index = np.argmax(matrix[row, :])
np.roll(matrix[row, :], middle-max_index)
我认为 argmax 可以提取所有行的所有最大值索引。但是如何对每一行应用不同的移位,np.roll 没有提供这样的功能,因为移位必须是一个 int 而不是一个数组。
这将是一种 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]])