import csv def change_fourth_occurrence(matrix): for col in range(len(matrix[0])): count = 1 for row in range(1, len(matrix)): if matrix[row][col] == matrix[row - 1][col]: count += 1 else: count = 1 if count == 4: next_number = matrix[row][col] + 1 while next_number in matrix[:, col]: next_number += 1 matrix[row][col] = next_number count = 1 # Read the matrix from CSV input_matrix = [] with open('matrix2.csv', 'r') as file: csv_reader = csv.reader(file) for row in csv_reader: input_matrix.append([int(num) for num in row]) # Convert the matrix to a NumPy array for easy column indexing import numpy as np input_matrix = np.array(input_matrix) # Call the function to modify the matrix change_fourth_occurrence(input_matrix) # Write the modified matrix back to CSV with open('matrix5.csv', 'w', newline='') as file: csv_writer = csv.writer(file) csv_writer.writerows(input_matrix)