【问题标题】:Other form to Index in PythonPython中索引的其他形式
【发布时间】:2020-10-07 22:05:29
【问题描述】:

我正在学习机器学习课程,并且在回顾 numpy 库时,使用了一种我以前从未见过的索引方法。我们定义了a = np.array([[1,2],[3,4],[5,6]])。随后创建了两个新数组:np.array([a[0,0], a[1,1], a[2,1]]。这是我知道的索引方式。我不知道的索引方式是这样的:print(a[[0,1,2],[0,1,1]])。有人可以帮我解释一下这种最新的索引形式吗?

【问题讨论】:

  • 这是另一个很好地解释索引的教程:check out

标签: python numpy indexing


【解决方案1】:

n 数组被传递时,其中n 是数组维度的数量,它们被用作对应维度的索引。 a[[0,1,2],[0,1,1]] 等价于[a[0,0], a[1,1], a[2,1]]

让我引用numpy docs:

... 从每一行中,应该选择一个特定的元素。该行 index 只是 [0, 1, 2] 并且列索引指定要 选择相应的行,此处为 [0, 1, 0]。两者一起使用 该任务可以使用高级索引来解决:

x = np.array([[1, 2], [3, 4], [5, 6]])

x[[0, 1, 2], [0, 1, 0]]
array([1, 4, 5])

【讨论】:

    【解决方案2】:

    它调用integer array indexing。在您的示例中,您正在访问一个名为 a 的 1x3 数组的 [[0,1,2],[0,1,1]] 索引。这意味着,您来自a

    [
        the first element of the first array,contained in this 1x3 array,
        the second element of the second array, contained in this big array,
        the second element of the third array, contained in the same array
    ]
    

    打印出来,你会得到[1 4 6]的输出,因为那些是指定位置的元素((0,0),(1,1),(2,1))。您可以将其可视化为列和行方案

    [[rows],[colums]] # vertically speaking
    

    您在第一个子数组中选择所需项目的行,在第二个子数组中选择列。

    【讨论】:

      猜你喜欢
      • 2013-08-15
      • 2016-01-07
      • 2014-09-09
      • 1970-01-01
      • 2020-03-24
      • 2015-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多