python - 在 NumPy 中使用 2 个维度进行索引时出错

标签 python numpy slice

为什么这样做:

>>> (tf[:,[91,1063]])[[0,3,4],:]
array([[ 0.04480133,  0.01079433],
       [ 0.11145042,  0.        ],
       [ 0.01177578,  0.01418614]])

但这不是:

>>> tf[[0,3,4],[91,1063]]
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (3,) (2,) 

我做错了什么?

最佳答案

tf[:,[91,1063]])[[0,3,4],:]

分两步操作,首先选择 2 列,然后从该结果中选择 3 行

tf[[0,3,4],[91,1063]]

尝试选择 tf[0,91] , tf[3,1063]ft[4, oops] .

tf[[[0],[3],[4]], [91,1063]]

应该工作,给出与第一个表达式相同的结果。将第一个列表视为一列,选择行。

tf[np.array([0,3,4])[:,newaxis], [91,1063]]

是生成该列索引数组的另一种方式

tf[np.ix_([0,3,4],[91,1063])]

np.ix_可以帮助生成这些索引数组。

In [140]: np.ix_([0,3,4],[91,1063])
Out[140]: 
(array([[0],
        [3],
        [4]]), array([[  91, 1063]]))

这些列和行数组一起广播产生一个二维坐标数组

[[(0,91), (0,1063)]
 [(3,91), ...     ]
 ....             ]]

这是文档的相关部分:http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#purely-integer-array-indexing

我基本上是在重复我对 Composite Index updates for Numpy Matrices 的回答

关于python - 在 NumPy 中使用 2 个维度进行索引时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30176268/

相关文章:

python - bool 矩阵形式 Python 的列表字典

python - 在 NumPy 中交换数组数据

go - 一段任意结构的接口(interface)用作函数参数(golang)

python - “numpy”没有属性 'core'

arrays - golang如何将类型转换为字节数组

multithreading - 二维 slice 的线程安全性,其中每个线程在第一维中都有自己的索引

python - pandas groupby 数字条纹

python - Miniconda3 安装失败,错误 "python-3.7.1-h0371630_7/bin/python: not found"

python - 如何从 python 字典中返回特定信息?

python - PyTables 有什么优势?