Group 2D numpy array elements which have equal 1st column values

后端 未结 1 1517
遥遥无期
遥遥无期 2021-01-26 02:30

I have a 2D numpy array like this

[[ 569  897]
 [ 570  898]
 [ 570  900]
 [ 571  901]
 [ 571  905]
 [ 572  906]]

I want the elements wh

相关标签:
1条回答
  • 2021-01-26 03:03

    You can use np.unique to get the separating indices and then use np.split to actually split -

    np.split(a, np.unique(a[:,0], return_index=1)[1][1:],axis=0)
    

    Alternatively, with slicing and using np.flatnonzero -

    np.split(a, np.flatnonzero(a[1:,0] != a[:-1,0])+1,axis=0)
    

    Sample run -

    In [63]: a
    Out[63]: 
    array([[569, 897],
           [570, 898],
           [570, 900],
           [571, 901],
           [571, 905],
           [572, 906]])
    
    In [64]: out = np.split(a, np.flatnonzero(a[1:,0] != a[:-1,0])+1,axis=0)
    
    In [65]: out[0]
    Out[65]: array([[569, 897]])
    
    In [66]: out[1]
    Out[66]: 
    array([[570, 898],
           [570, 900]])
    
    In [67]: out[2]
    Out[67]: 
    array([[571, 901],
           [571, 905]])
    
    In [68]: out[3]
    Out[68]: array([[572, 906]])
    
    0 讨论(0)
提交回复
热议问题