Match along last axis in numpy array

后端 未结 1 1835
庸人自扰
庸人自扰 2021-01-28 07:20

I saw a lot of articles and answers to other questions about slicing 3D lists in python, but I can\'t apply those methods to my case.

I have a 3D list:

l         


        
1条回答
  •  抹茶落季
    2021-01-28 08:05

    Using numpy, you can slice the array to keep the last two elements on the last axis, find the indices where each pair takes place, flatten the result and use it to slice the array:

    a = np.array(my_list) # don't call your list "list"
    
    a_sliced = a[...,1:]
    
    ix1 = np.flatnonzero((a_sliced  == pair1).all(-1).ravel()).item()
    
    ix2 = np.flatnonzero((a_sliced  == pair2).all(-1).ravel()).item()
    
    np.concatenate(a)[ix1:ix2+1]
    
    array([[ 4, 86, 90],
           [ 7, 87, 34],
           [ 1, 49, 76],
           [ 0, 76, 78]])
    

    a being defined as a numpy array, and both pairs defined as tuples:

    pair1 = 86, 90
    pair2 = 76, 78
    

    0 讨论(0)
提交回复
热议问题