【问题标题】:Sort the numpy matrix by the minimum values and display minimum values on the diagonal of matrix按最小值对 numpy 矩阵进行排序,并在矩阵的对角线上显示最小值
【发布时间】:2016-11-29 22:02:01
【问题描述】:

无论其他元素如何定位,重要的只有沿对角线的值。

例如我有矩阵:

matrix = [[1, 3, 2],
          [2, 5, -9],
          [3, 4, 6]]

我想要达到的目标是:

[[-9, 3, 2],
 [6, 1, 5],
 [3, 4, 2]]

我试过了:

>>> np_matrix = np.array(matrix)
>>> np_matrix.diagonal()
array([1, 5, 6])

>>> np.sort(np_matrix)
array([[ 1,  2,  3],
       [-9,  2,  5],
       [ 3,  4,  6]])

我认为我可以从这些方法中得到一些东西,但我不知道如何让它们一起工作。感谢我能得到的所有帮助。

【问题讨论】:

  • 你的矩阵总是 3x3 吗?

标签: python numpy matrix


【解决方案1】:

我不太确定你想要什么。但也许像

sorted = np.sort(matrix, axis=None) #sorts flattened matrix

现在你已经重塑它,然后用第一行改变对角线元素:

sorted.shape = matrix.shape
for i in xrange(1, matrix.shape[0]):  # first element already in order
     sorted[0, i], sorted[i, i] = sorted[i, i], sorted[0, i]

但老实说,我首先会质疑这是否真的是你想要的。这对我来说似乎并没有什么用处。获得一个包含最小元素的数组难道还不够吗

diag_lowest = np.sort(matrix, axis=None)[:matrix.shape[0]]

并保持矩阵不变。

【讨论】:

  • 是否有理由更喜欢sorted.shape = matrix.shape 而不是使用ndarray.reshape?
  • 我真的不知道。对我来说,这个任务看起来很像 Python,因为这是实现 setters 的方式。但老实说我不知道​​,我认为在引擎盖下它会非常相似,只是reshape 提供了额外的order 设置。可能sorted.shape = ...、np.reshape(sroted, ...) 和sorted.reshape(...) 都做同样的事情,除非你使用order 参数。
  • 简短搜索给了我stackoverflow.com/questions/26856375/…。所以reshape 可能会创建一个副本,而shape = 如果无法创建视图则会导致错误。
  • 谢谢,它有效。您的代码中唯一有一个小错误,它必须是 sorted[0,i], sorted[i,i] = sorted[i,i], sorted[0,i]
猜你喜欢
  • 2012-04-22
  • 2012-08-17
  • 1970-01-01
  • 2017-03-19
  • 1970-01-01
  • 2017-05-24
  • 1970-01-01
  • 2012-10-14
  • 2017-10-30
相关资源
最近更新 更多