【问题标题】:I find indexing in python for numpy array weird我发现在 python 中为 numpy 数组编制索引很奇怪
【发布时间】:2023-04-05 05:50:01
【问题描述】:

我对 python 很陌生,我正在处理一些数据操作。 我以为 numpy 中的索引会是 [row][column],但这不是我在 python 中执行时看到的。 下面是一个简单的例子,说明 python 的行为方式。我不明白为什么最后两个命令得到相同的结果:

import numpy as num

test_arr = num.array([[1, 2, 3],[4, 5, 6], [7, 8, 9]],dtype=num.float32)

test_arr[0][:]
array([1., 2., 3.], dtype=float32)

test_arr[:][0]
array([1., 2., 3.], dtype=float32)

我期待

test_arr[0][:]
array([1., 2., 3.], dtype=float32)

test_arr[:][0]
array([1., 4., 7.], dtype=float32)

有人能解释一下为什么 python 的行为如此,以及如何获取所有行的第 0 个索引吗?

【问题讨论】:

  • 即使使用 Python 列表 [:] 也只会创建一个副本;使用数组它是一个视图。所以在你的例子中它什么也没做。每个[] 都是一个单独的索引步骤。花点时间阅读 numpy 基础知识,例如这个索引页面:docs.scipy.org/doc/numpy/reference/arrays.indexing.html

标签: python arrays numpy indexing


【解决方案1】:

要在 numpy 数组中获取一列,请使用 [:,n] 其中 n 是您的列号

test_arr[:,0]
array([1., 4., 7.], dtype=float32)

【讨论】:

    【解决方案2】:
    In  : import numpy as num
    
    In  : test_arr = num.array([[1, 2, 3],[4, 5, 6], [7, 8, 9]],dtype=num.float32)
    
    In  : test_arr[0,:]
    Out : [1. 2. 3.]
    
    In  : test_arr[:,0]
    Out : [1. 4. 7.]
    

    【讨论】:

      猜你喜欢
      • 2015-08-16
      • 1970-01-01
      • 2019-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多