0

I have a 2d numpy array of the form:

array = [[0,0,0,1,0], [0,1,0,0,0], [1,0,0,0,0]]

I'd like to go to each of the rows, iterate over the entries until the value 1 is found, then replace every subsequent value in that row to a 1. The output would then look like:

array = [[0,0,0,1,1], [0,1,1,1,1], [1,1,1,1,1]]

My actual data set is very large, so I was wondering if there is a specialized numpy function that does something like this, or if there's an obvious way to do it that I'm missing.

Thanks!

Ian Gullett
  • 107
  • 9
  • There's interesting related discussions in https://stackoverflow.com/questions/7632963/numpy-find-first-index-of-value-fast/7654768 , esp. the benchmarks in the 3rd answer – Demi-Lune Oct 02 '19 at 20:09

1 Answers1

0

You can use apply.

import numpy as np

array = np.array([[0,0,0,1,0], [0,1,0,0,0], [1,0,0,0,0]])

def myfunc(l):
    i = 0
    while(l[i]!=1):
        i+=1
    return([0]*i+[1]*(len(l)-i))

print(np.apply_along_axis(myfunc, 1, array))
kpie
  • 9,588
  • 5
  • 28
  • 50