【问题标题】:How does slice indexing work in numpy array切片索引如何在 numpy 数组中工作
【发布时间】:2019-08-30 01:57:42
【问题描述】:

假设我们有一个数组

a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])

现在我有下面

row_r1 = a[1, :]
row_r2 = a[1:2, :]

print(row_r1.shape)
print(row_r2.shape)

我不明白为什么 row_r1.shape 是 (4,) 而 row_r2.shape 是 (1,4)

它们的形状不应该都等于(4,)吗?

【问题讨论】:

  • 当您指定一个范围而不是单个数字时,它会将该范围作为轴返回。如果范围“恰好是”大小为 1,它不会改变您要求切片(在该维度中)而不是单个元素(这将删除维度)这一事实。希望很清楚
  • 文档很清楚。使用标量进行索引会减少维度。切片没有。问题 - 列表索引如何工作?

标签: python numpy numpy-ndarray


【解决方案1】:

我喜欢这样想。第一种方式row[1, :],状态去获取我第 1 行的所有值,如下所示:

返回: array([5, 6, 7, 8])

形状

(4,) numpy 数组中的四个值。

作为第二个row[1:2, :],各州给我获取索引 1 和索引 2 之间的数据片段:

返回:

array([[5, 6, 7, 8]]) 注意:双括号

形状

(1,4) np.array 的一行中有四个值。

【讨论】:

    【解决方案2】:

    它们的形状不同,因为它们不是同一个东西。您可以通过打印它们来验证:

    import numpy as np
    
    a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
    
    row_r1 = a[1, :]
    row_r2 = a[1:2, :]
    
    print("{} is shape {}".format(row_r1, row_r1.shape))
    print("{} is shape {}".format(row_r2, row_r2.shape))
    

    产量:

    [5 6 7 8] is shape (4,)
    [[5 6 7 8]] is shape (1, 4)
    

    这是因为索引将返回一个元素,而切片将返回一个数组。但是,您可以使用 numpy 数组可用的 .resize() 函数将它们操作为相同的东西。 代码:

    import numpy as np
    
    a = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
    
    row_r1 = a[1, :]
    row_r2 = a[1:2, :]
    
    print("{} is shape {}".format(row_r1, row_r1.shape))
    print("{} is shape {}".format(row_r2, row_r2.shape))
    # Now resize row_r1 to be the same shape
    row_r1.resize((1, 4))
    print("{} is shape {}".format(row_r1, row_r1.shape))
    print("{} is shape {}".format(row_r2, row_r2.shape))
    

    产量

    [5 6 7 8] is shape (4,)
    [[5 6 7 8]] is shape (1, 4)
    [[5 6 7 8]] is shape (1, 4)
    [[5 6 7 8]] is shape (1, 4)
    

    表明您实际上现在正在处理相同形状的对象。希望这有助于清除它!

    【讨论】:

      猜你喜欢
      • 2015-01-21
      • 1970-01-01
      • 2017-06-24
      • 1970-01-01
      • 2014-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多