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

'''

 



answered Jul 9, 2024 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]]

'''

 



answered Jul 9, 2024 by avibootz
...