Home > Net >  fastest way too fill a rows that contain all zeros
fastest way too fill a rows that contain all zeros

Time:08-24

what is the fastest way to fill every row in 2d array that contains all zeros with different value.

Only the rows that all contain Zero..

the only idea I have is a loop and using np.all() to check every row

array([[2, 6, 9, 7, 0],
       [0, 0, 0, 0, 0],
       [3, 8, 5, 4, 7]])

array([[2, 6, 9, 7, 0],
       [1, 1, 1, 1, 1],
       [3, 8, 5, 4, 7]])

CodePudding user response:

Well, if this is sufficient:

a = np.array([[2, 6, 9, 7, 0],
              [0, 0, 0, 0, 0],
              [3, 8, 5, 4, 7]])

a[~a.any(axis=1)] = 1

Slight note: I use ~np.any(...) instead of np.all(a==0) because the a array is larger than the boolean array returned by all or any. The a==0 creates a 2D boolean array. Negating the 1D boolean array created by any requires less work and memory.

  • Related