【问题标题】:Shift matrix rows to have maxima in the middle移动矩阵行以在中间具有最大值
【发布时间】:2015-10-06 02:01:33
【问题描述】:

这可以通过 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 而不是数组这样的功能。

【问题讨论】:

  • 您可以通过提供您迄今为止尝试过的代码将其转换为一个好问题!
  • 我编辑了我的问题。

标签: python numpy matrix vectorization shift


【解决方案1】:

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

【讨论】:

  • 谢谢,正是我想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-27
相关资源
最近更新 更多