简体   繁体   中英

fastest way too fill a rows that contain all zeros

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]])
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM