【问题标题】:Subsetting 2D NumPy Arrays对二维 NumPy 数组进行子集化
【发布时间】:2023-02-08 01:31:34
【问题描述】:

你好我在学习 python 的道路上,我正在努力理解这个问题你能帮我解决这个问题吗

打印出 np_baseball 的第 50 行。 为什么这个命令的答案是 [49, :] 从我的角度来看,如果要求第 50 个,它应该只是 [49] 为什么还有额外的:

非常高兴您的回复

【问题讨论】:

  • 如果你有一个二维数组,[49][49, :] 会做同样的事情。 [49] 是正确的。
  • 您将如何打印 5th 列?行选择有何不同?

标签: python numpy 2d subset


【解决方案1】:

numpy doc on slicing 声明:

如果选择元组中的对象数小于 N,则 : 假定为任何后续维度。

所以这两个版本实际上是一样的。

文档给出的示例是这样的:

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

【讨论】:

    【解决方案2】:

    看起来你正在使用这个course

    https://github.com/datacamp/courses-introduction-to-python/blob/master/chapter4.md

    看看这段代码:

    # baseball is available as a regular list of lists
    
    # Import numpy package
    import numpy as np
    
    # Create np_baseball (2 cols)
    np_baseball = np.array(baseball)
    
    # Print out the 50th row of np_baseball
    print(np_baseball[49,:])
    
    # Select the entire second column of np_baseball: np_weight_lb
    np_weight_lb = np_baseball[:,1]
    
    # Print out height of 124th player
    print(np_baseball[123, 0])
    

    请注意,选择列的下一行使用 [:,1] 表示法:

    np_baseball[:,1]
    

    这里需要“:”来识别/切片第一个维度,行。在np_baseball[49,:] 中,':' 做同样的事情,对二维进行切片。但作为简写,不需要指定尾随尺寸,所以 np_baseball[49] 就可以了。

    在编写指导性答案时,我喜欢包含尾部切片,即使代码不需要它。我认为这让事情更清楚(大多数 :) ) 人类读者。

    【讨论】:

      【解决方案3】:
      # baseball is available as a regular list of lists
      
      # Import numpy package
      import numpy as np
      
      # Create np_baseball (2 cols)
      np_baseball = np.array(baseball)
      
      # Print out the 50th row of np_baseball
      print(np_baseball[49:50])
      
      # Select the entire second column of np_baseball: np_weight_lb
      np_weight_lb=np_baseball[:,1]
      
      # Print out height of 124th player
      print(np_baseball[123, 0])
      

      【讨论】:

        猜你喜欢
        • 2015-09-04
        • 2013-06-29
        • 2021-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-20
        • 2016-09-12
        • 1970-01-01
        相关资源
        最近更新 更多