Make numpy matrix more sparse
问题 Suppose I have a numpy array np.array([ [3, 0, 5, 3, 0, 1], [0, 1, 2, 1, 5, 2], [4, 3, 5, 3, 1, 4], [2, 5, 2, 5, 3, 1], [0, 1, 2, 1, 5, 2], ]) Now, I want to randomly replace some elements with 0. So that I have an output like this np.array([ [3, 0, 0, 3, 0, 1], [0, 1, 2, 0, 5, 2], [0, 3, 0, 3, 1, 0], [2, 0, 2, 5, 0, 1], [0, 0, 2, 0, 5, 0], ]) 回答1: We can use np.random.choice(..., replace=False) to randomly select a number of unique non-zero flattened indices and then simply index and reset