Searching a sequence in a NumPy array

前端 未结 2 1996
[愿得一人]
[愿得一人] 2020-12-06 08:15

Let\'s say I have the following array :

 array([2, 0, 0, 1, 0, 1, 0, 0])

How do I get the indices where I have occurrence of sequence of va

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-06 08:42

    I find that the most succinct, intuitive and general way to do this is using regular expressions.

    import re
    import numpy as np
    
    # Set the threshold for string printing to infinite
    np.set_printoptions(threshold=np.inf)
    
    # Remove spaces and linebreaks that would come through when printing your vector
    yourarray_string = re.sub('\n|\s','',np.array_str( yourarray ))[1:-1]
    
    # The next line is the most important, set the arguments in the braces
    # such that the first argument is the shortest sequence you want
    # and the second argument is the longest (using empty as infinite length)
    
    r = re.compile(r"[0]{1,}") 
    zero_starts = [m.start() for m in r.finditer( yourarray_string )]
    zero_ends = [m.end() for m in r.finditer( yourarray_string )]
    

提交回复
热议问题