索引具有2个索引列表的2D Numpy数组我有一个奇怪的情况。我有一个2D Numpy数组,x:x = np.random.random_integers(0,5,(20,8))我有2个索引器 - 一个带有行的索引,另一个带有索引。为了索引X,我必须执行以下操作:row_indices = [4,2,18,16,7,19,4]col_indices = [1,2]x_rows = x[row_indices,:]x_indexed = x_rows[:,column_indices]而不仅仅是:x_new = x[row_indices,column_indices](失败的:错误,无法用(2,)广播(20,))我希望能够使用广播在一行中进行索引,因为这样可以保持代码的清晰和可读性......而且,我不知道所有关于python的内容,但据我所知它,它应该更快一行(我将使用相当大的数组)。测试用例:x = np.random.random_integers(0,5,(20,8))row_indices = [4,2,18,16,7,19,4]col_indices = [1,2]x_rows = x[row_indices,:]x_indexed = x_rows[:,col_indices]x_doesnt_work = x[row_indices,col_indices]
3 回答

小怪兽爱吃肉
TA贡献1852条经验 获得超1个赞
import numpy as np x = np.random.random_integers(0,5,(4,4))x array([[5, 3, 3, 2], [4, 3, 0, 0], [1, 4, 5, 3], [0, 4, 3, 4]])# This indexes the elements 1,1 and 2,2 and 3,3indexes = (np.array([1,2,3]),np.array([1,2,3]))x[indexes]# returns array([3, 5, 4])
请注意,numpy具有非常不同的规则,具体取决于您使用的索引类型。所以索引几个要素应该是由tuple
的np.ndarray
(见索引手册)。
因此,您只需要转换list
为np.ndarray
,它应该按预期工作。
添加回答
举报
0/150
提交
取消