Python - slice array until certain condition is met
Question: I need to slice an array from a given index until a certain condition is met.

    
    
    >>> a = numpy.zeros((10), dtype='|S1')
    >>> a[2] = 'A'
    >>> a[4] = 'X'
    >>> a[8] = 'B'
    >>> a
    array(['', '', 'A', '', 'X', '', '', '', 'B', ''], dtype='|S1')
    

For instance, for the above array I want a subset from a given index until
first non-zero values in both directions. For example, for index values 2, 4,
8 the results would be:

    
    
    ['', '', A, '']      # 2
    ['', X, '', '', '']  # 4
    ['', '', '', B, '']  # 8
    

Any suggestions on the simplest way to do this using the numpy API? Learning
python and numpy, would appreciate any help. Thanks!


Answer: If you set up your problem like this:

    
    
    import numpy
    a = numpy.zeros((10), dtype=str)
    a[2] = 'A'
    a[4] = 'X'
    a[8] = 'B'
    

You can easily get the indices of non-empty strings like so:

    
    
    i = numpy.where(a!='')[0]  # array([2, 4, 8])
    

Alternatively, `numpy.argwhere(..)` also works well.

Then you can slice away using this array:

    
    
    out2 = a[:i[1]]        # 2   ['' '' 'A' '']
    out4 = a[i[0]+1:i[2]]  # 4   ['' 'X' '' '' '']
    

etc.

