In [435]: ref = np.array([[1,0],[0,1]])
In [436]: index = np.array([1.,1.,1.,0.,1.])
使用浮点数进行索引在最近的版本中会出现错误:
In [437]: ref[index,:]
IndexError Traceback (most recent call last)
<ipython-input-437-d50c95668d6c> in <module>()
IndexError: arrays used as indices must be of integer (or boolean) type
使用整数进行索引,在ref
中根据index
值选择行:
In [438]: ref[index.astype(int),:]
Out[438]:
array([[0, 1],
[0, 1],
[0, 1],
[1, 0],
[0, 1]])
这是一个应该使用
choose
的情况,但它对数组的形状更为挑剔,与上述索引方式不同:
In [440]: np.choose(index.astype(int)[:,None],[[1,0],[0,1]])
Out[440]:
array([[0, 1],
[0, 1],
[0, 1],
[1, 0],
[0, 1]])
如果只有两个转换为布尔值的选择,可以使用where
:
In [443]: np.where(index.astype(bool)[:,None],[0,1],[1,0])
Out[443]:
array([[0, 1],
[0, 1],
[0, 1],
[1, 0],
[0, 1]])