python - 从 NumPy 数组中选择特定的行和列

标签 python arrays numpy multidimensional-array numpy-slicing

我一直想弄清楚我在这里做错了什么愚蠢的事情。

我正在使用 NumPy,并且我有要从中选择的特定行索引和特定列索引。这是我的问题的要点:

import numpy as np

a = np.arange(20).reshape((5,4))
# array([[ 0,  1,  2,  3],
#        [ 4,  5,  6,  7],
#        [ 8,  9, 10, 11],
#        [12, 13, 14, 15],
#        [16, 17, 18, 19]])

# If I select certain rows, it works
print a[[0, 1, 3], :]
# array([[ 0,  1,  2,  3],
#        [ 4,  5,  6,  7],
#        [12, 13, 14, 15]])

# If I select certain rows and a single column, it works
print a[[0, 1, 3], 2]
# array([ 2,  6, 14])

# But if I select certain rows AND certain columns, it fails
print a[[0,1,3], [0,2]]
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# ValueError: shape mismatch: objects cannot be broadcast to a single shape

为什么会这样?当然,我应该能够选择第一、第二和第四行,以及第一和第三列?我期待的结果是:

a[[0,1,3], [0,2]] => [[0,  2],
                      [4,  6],
                      [12, 14]]

最佳答案

正如 Toan 所建议的,一个简单的技巧是先选择行,然后选择 上的列。

>>> a[[0,1,3], :]            # Returns the rows you want
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [12, 13, 14, 15]])
>>> a[[0,1,3], :][:, [0,2]]  # Selects the columns you want as well
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

[编辑] 内置方法:np.ix_

我最近发现 numpy 为您提供了一种内置的单线器,可以完全按照@Jaime 的建议进行操作,但不必使用广播语法(由于缺乏可读性)。来自文档:

Using ix_ one can quickly construct index arrays that will index the cross product. a[np.ix_([1,3],[2,5])] returns the array [[a[1,2] a[1,5]], [a[3,2] a[3,5]]].

所以你可以这样使用它:

>>> a = np.arange(20).reshape((5,4))
>>> a[np.ix_([0,1,3], [0,2])]
array([[ 0,  2],
       [ 4,  6],
       [12, 14]])

它的工作方式是按照 Jaime 建议的方式对齐数组,以便正确进行广播:

>>> np.ix_([0,1,3], [0,2])
(array([[0],
        [1],
        [3]]), array([[0, 2]]))

此外,正如 MikeC 在评论中所说,np.ix_ 具有返回 View 的优势,而我的第一个(预编辑)答案没有。这意味着您现在可以分配到索引数组:

>>> a[np.ix_([0,1,3], [0,2])] = -1
>>> a    
array([[-1,  1, -1,  3],
       [-1,  5, -1,  7],
       [ 8,  9, 10, 11],
       [-1, 13, -1, 15],
       [16, 17, 18, 19]])

关于python - 从 NumPy 数组中选择特定的行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22927181/

相关文章:

python - 如何在 Pandas 中正确找到偏度和峰度?

python - 具有链式比较的 PyCharm 键入警告

python - 错误 1064 (4200) - 当我在 MySQL 中输入 GRANT ALL 请求时

python - 将图像转换为二进制文件后,无法在带有matplotlib的笔记本中显示图像

从输入生成 Python 列表

ios - 在 Objective C 中添加二维数组的对角线

c - 在 Sakamoto 算法中查找 t[] 数组来查找星期几

arrays - 如何将 AD 计算机名称传递给数组?

python-3.x - Matplotlib - 带日期的水平条形图时间线 - Xticks 不显示日期

python - 值错误: Found input variables with inconsistent numbers of samples: [100, 300]