Finding False-True transitions in a numpy array

前端 未结 2 923
逝去的感伤
逝去的感伤 2020-12-30 15:34

Given a numpy array:

x = np.array([False, True, True, False, False, False, False, False, True, False])

How do I find the number of times th

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-30 16:15

    I kind of like to use numpy method "roll" for this kind of problems... "roll" rotates the array to left some step length : (-1,-2,...) or to right (1,2,...)

    import numpy as np
    np.roll(x,-1)
    

    ...this will give x but shifted one step to the left:

    array([ True,  True, False, False, False, False, False,  True, False, False], 
    dtype=bool)
    

    A False followed by a True can then be expressed as:

    ~x & np.roll(x,-1)
    
    array([ True, False, False, False, False, False, False,  True, False, False], 
    dtype=bool)
    

提交回复
热议问题