[Python] How to change random index positions in numpy array

Discussão em 'Python' iniciado por Stack, Abril 26, 2025.

  1. Stack

    Stack Membro Participativo

    I have a numpy array that looks like this:

    array([[0.5, 0.2, 0.6],
    [0.8, 0.1, 0.3],
    [0.4, 0.5, 0.4],
    [0.3, 0.2, 0.9]])


    I want to change 50% of the values in the 3rd column into a random value. How can I do this efficiently? This operation will have to be performed hundreds of thousands of times, so efficiency is very important here. The output can look like this:

    array([[0.5, 0.2, 0.2],
    [0.8, 0.1, 0.3],
    [0.4, 0.5, 0.4],
    [0.3, 0.2, 0.1]])


    I first thought about isolating this column, then replacing some of the values, and then moving this column back into the original matrix.

    last_column = array[:,2]
    last_column = change_values_randomly(last_column)
    np.c_[array[:,:2], last_column]


    How do I change 50% of these values randomly?

    Continue reading...

Compartilhe esta Página