Make numpy matrix more sparse

前端 未结 2 429
栀梦
栀梦 2021-01-23 02:25

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


        
2条回答
  •  不要未来只要你来
    2021-01-23 02:36

    Use np.ravel or the ravel method to create a flattened. Note that the flatten method always creates a copy, so mutating won't work.

    a = 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],
    ])
    r = a.ravel()
    r[random.randrange(0, len(r))] = 0
    

提交回复
热议问题