为什么这样做:
>>> (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/