[英]Select using multiple arrays of indices from an ndarray in numpy
Say if I have a 2D array:假设我有一个二维数组:
y = np.arange(35).reshape(5,7)
# array([[ 0, 1, 2, 3, 4, 5, 6],
# [ 7, 8, 9, 10, 11, 12, 13],
# [14, 15, 16, 17, 18, 19, 20],
# [21, 22, 23, 24, 25, 26, 27],
# [28, 29, 30, 31, 32, 33, 34]])
and select the 2nd and 3rd elements of the 1st, 3rd and 5th array like so:和 select 第一个、第三个和第五个数组的第二个和第三个元素,如下所示:
y[np.array([0,2,4]), 1:3]
# array([[ 1, 2],
# [15, 16],
# [29, 30]])
I cannot find a way to replicate this using arrays in place of the slice for indexing, the following doesn't work, I must be able to use arrays to index as I sometimes might be interested in the 2nd and 4th elements of the arrays and so on:我找不到使用 arrays 代替索引切片的方法来复制它,以下方法不起作用,我必须能够使用 arrays 进行索引,因为我有时可能对 ZA3CBC53F9D671D9CZ 的第二个和第四个元素感兴趣很快:
y[np.array([0,2,4]), np.array([1,2])]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (3,) (2,)
How can I achieve my desired functionality?如何实现我想要的功能?
np.ix_() is designed for this type of problem. np.ix_() 专为此类问题而设计。
def getSub():
y = np.arange(35).reshape(5,7)
locs = np.ix_([0,2,4],[1,2])
return y[locs]
>>> getSub()
array([[ 1, 2],
[15, 16],
[29, 30]])
y[np.array([0,2,4]), np.array([[1],[2]])].T
you can try to use this y[np.array([[0,2,4]]*2),np.array([[1]*3,[2]*3])].T
你可以尝试使用这个
y[np.array([[0,2,4]]*2),np.array([[1]*3,[2]*3])].T
Quick, dirty way to achieve it with double indexing.通过双索引实现它的快速、肮脏的方法。
y[np.array([0,2,4]),:][:,np.array([1,2])]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.