Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Semrush - keyword research tool

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Teach Your Child To Read

Disclosure: My content contains affiliate links.

31,615 questions

41,668 answers

573 users

How to set every row and column in a matrix to 0 if that row or column contains a 0 in Python

2 Answers

0 votes
import pprint

def set_zeros(matrix):
    rows, cols = len(matrix), len(matrix[0])
    
    hasZeroInFirstRow = any(matrix[0][j] == 0 for j in range(cols))
    hasZeroInFirstCol = any(matrix[i][0] == 0 for i in range(rows))

    for i in range(1, rows):
        for j in range(1, cols):
            if matrix[i][j] == 0:
                matrix[i][0] = matrix[0][j] = 0

    for i in range(1, rows):
        for j in range(1, cols):
            if matrix[i][0] == 0 or matrix[0][j] == 0:
                matrix[i][j] = 0

    if hasZeroInFirstRow:
        matrix[0] = [0] * cols
    if hasZeroInFirstCol:
        for i in range(rows):
            matrix[i][0] = 0


matrix = [[1, 0, 1, 1, 0],
          [0, 1, 1, 1, 0],
          [1, 1, 1, 1, 1],
          [1, 0, 1, 1, 1],
          [1, 1, 1, 1, 1]]
          
set_zeros(matrix)

pprint.pprint(matrix)




'''
run:

[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 1, 1, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 1, 1, 0]]

'''

 



Learn & Practice Python
with the most comprehensive set of 13 hands-on online Python courses
Start now


answered 3 days ago by avibootz
0 votes
import pprint
import pandas as pd

def set_zeros_pandas(matrix):
    df = pd.DataFrame(matrix)
    df_result = df.copy(deep = True)
    df_result.loc[df.eq(0).any(axis = 1)] = 0
    df_result.loc[:, df.eq(0).any(axis = 0)] = 0
    
    return df_result.values.tolist()


matrix = [[1, 0, 1, 1, 0],
          [0, 1, 1, 1, 0],
          [1, 1, 1, 1, 1],
          [1, 0, 1, 1, 1],
          [1, 1, 1, 1, 1]]
          
matrix = set_zeros_pandas(matrix)

pprint.pprint(matrix)



'''
run:

[[0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 1, 1, 0],
 [0, 0, 0, 0, 0],
 [0, 0, 1, 1, 0]]

'''

 



Learn & Practice Python
with the most comprehensive set of 13 hands-on online Python courses
Start now


answered 3 days ago by avibootz
...