【问题标题】:Indexing in Python using Array of indexes在 Python 中使用索引数组进行索引
【发布时间】:2016-04-27 23:32:32
【问题描述】:

所以,我有这个矩阵是M=60x8

然后我使用z= M.argmax(axis=1) 为每一行找到最大元素 因此z is a 60 element array 包含从 0 到 7 的索引。

除了使用循环进行迭代的老式方法之外,我是否可以在 python 中使用某种矢量化代码,以便使用 z 矩阵打印我得到最大值的 M 的值。

【问题讨论】:

标签: python arrays indexing vectorization


【解决方案1】:
import numpy as np

# define our matrix M
M = np.arange(6*8).reshape(6,8)

当我们看 M 时:

> M
> array(
  [[ 0,  1,  2,  3,  4,  5,  6,  7],
   [ 8,  9, 10, 11, 12, 13, 14, 15],
   [16, 17, 18, 19, 20, 21, 22, 23],
   [24, 25, 26, 27, 28, 29, 30, 31],
   [32, 33, 34, 35, 36, 37, 38, 39],
   [40, 41, 42, 43, 44, 45, 46, 47]])

> M.shape
> (6, 8)

现在我们得到每一行的最大参数:

> z = np.argmax(M, axis=1)
> array([7, 7, 7, 7, 7, 7])

因此,我们得到了每一行的最大元素的索引。如果我们想取回这些值,我们可以简单地对 M 进行切片:

> M[np.arange(M.shape[0]), z]
> array([ 7, 15, 23, 31, 39, 47])

np.arange(M.shape[0]) 为每一行创建索引,而z 覆盖列的索引。因此,我们正在提取每一行的第 n 个元素(根据z 的条目)。


为了证明这适用于任意“排序”数组:

> M2 = np.ravel(np.copy(M))
> np.random.shuffle(M2)
> M2 = M2.reshape(M.shape[0], M.shape[1])
> M2
> array(
  [[34, 16,  5, 32, 31,  2, 17, 38],
   [33, 18,  9, 46, 20,  4, 39, 30],
   [10, 41, 35, 23,  0, 24, 45, 14],
   [28, 36,  8, 22, 11, 15,  7, 44],
   [27,  1, 25,  6,  3, 19, 47, 37],
   [40, 42, 29, 21, 12, 43, 26, 13]])

> z2 = np.argmax(M2, axis=1)
> array([7, 3, 6, 7, 6, 5])

> M2[np.arange(M2.shape[0]), z2]
> array([38, 46, 45, 44, 47, 43])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-02
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    • 2017-08-19
    • 1970-01-01
    相关资源
    最近更新 更多