移动矩阵行以在中间具有最大值

时间:2015-07-16 14:39:04

标签: python numpy matrix vectorization shift

这可以用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并没有提供这样的功能,因为shift必须是int而不是数组。

1 个答案:

答案 0 :(得分:4)

这是一种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]])