Subsetting a 2D numpy array

前端 未结 4 1222
暖寄归人
暖寄归人 2020-11-27 07:28

I have looked into documentations and also other questions here, but it seems I have not got the hang of subsetting in numpy arrays yet.

I have a numpy array, and

4条回答
  •  抹茶落季
    2020-11-27 07:36

    You could use np.meshgrid to give the n1, n2 arrays the proper shape to perform the desired indexing:

    In [104]: a[np.meshgrid(n1,n2, sparse=True, indexing='ij')]
    Out[104]: 
    array([[ 0,  1,  2,  3,  4],
           [10, 11, 12, 13, 14],
           [20, 21, 22, 23, 24],
           [30, 31, 32, 33, 34],
           [40, 41, 42, 43, 44]])
    

    Or, without meshgrid:

    In [117]: a[np.array(n1)[:,np.newaxis], np.array(n2)[np.newaxis,:]]
    Out[117]: 
    array([[ 0,  1,  2,  3,  4],
           [10, 11, 12, 13, 14],
           [20, 21, 22, 23, 24],
           [30, 31, 32, 33, 34],
           [40, 41, 42, 43, 44]])
    

    There is a similar example with an explanation of how this integer array indexing works in the docs.

    See also the Cookbook recipe Picking out rows and columns.

提交回复
热议问题