fastest way too fill a rows that contain all zeros

Question:

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]])
Asked By: sten

||

Answers:

import numpy as np

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

rowi_0 = (a==0).all(axis=1)
 
for idx, val in enumerate(rowi_0):
    if val == True:
        a[idx] = np.random.randint(10, size=a.shape[1])

print(a)

I think this is the easiest and fast way, rewriting migth take little bit of time tho, but loops work fine for this scenario

Answered By: Ogabek

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.

Answered By: Homer512
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.