Zero rest of array string when 0 or less is true

I have an MxN array. I want to zero out all values ​​after the item in the string is zero or less.

For example a 2x12 array

111110011111
112321341411

      

should turn into

111110000000
112321341411

      

Thank!

+3


source to share


2 answers


This is not the most efficient method, but I used np.cumsum for these types of things.

>>> import numpy as np

>>> dat = np.array([[1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1],
                    [1, 1, 2, 3, 2, 1, 3, 4, 1, 4, 1, 1], ])

>>> dat[np.cumsum(dat <= 0, 1, dtype='bool')] = 0

>>> print(dat)
array([[1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
       [1, 1, 2, 3, 2, 1, 3, 4, 1, 4, 1, 1]])

      




@Jaime just pointed out which np.logical_or.accumulate(dat <= 0, axis=1)

is probably better than np.cumsum.

+5


source


Maybe you or someone else needs an alternative solution without using numpy.



>>> dat = ['111110011111','112321341411','000000000000', '123456789120']
>>> def zero(dat):
    result = []
    for row in dat:
        pos = row.find('0')
        if pos > 0:
            result.append(row[0:pos] + ('0' * (len(row) - pos)))
        else:
            result.append(row)
    return result

>>> res = zero(dat)
>>> res
['111110000000', '112321341411', '000000000000', '123456789120']
>>> dat
['111110011111', '112321341411', '000000000000', '123456789120']

      

0


source







All Articles