Extract separate non-zero blocks from array

前端 未结 4 932
长发绾君心
长发绾君心 2020-12-30 13:05

having an array like this for example:

[1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1]

What\'s the fastest way in Pytho

4条回答
  •  自闭症患者
    2020-12-30 13:30

    Have a look at scipy.ndimage.measurements.label:

    import numpy as np
    from scipy.ndimage.measurements import label
    
    x = np.asarray([1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1])
    labelled, numfeats = label(x)
    indices = [np.nonzero(labelled == k) for k in np.unique(labelled)[1:]]
    

    indices contains exactly what you asked for. Note that, depending on your ultimate goal, labelled might also give you useful (extra) information.

提交回复
热议问题