Home > OS >  How to replace values of a 2d-array by an array of indices in python
How to replace values of a 2d-array by an array of indices in python

Time:09-22

I intend to replace the value of specific indices based on an array of indices. The original 2d-array is this:

    A=    [[0.         0.         0.         0.         0.         0.         0.        ]    

           [0.         1.98019867 1.96039735 1.90331502 1.81546888 1.70634771 0.        ]

           [0.         2.         1.98019867 1.92311635 1.83527021 1.72614904 0.        ]

           [0.         1.98019867 1.96039735 1.90331502 1.81546888 1.70634771 0.        ]

           [0.         1.92311635 1.90331502 1.84623269 1.75838656 1.64926538 0.        ]

           [0.         1.83527021 1.81546888 1.75838656 1.67054042 1.56141925 0.        ]

           [0.         0.         0.         0.         0.         0.         0.        ]]

and this is the array of indices (in each row, each pair indicates an index)

    index=[[1 2]
 [2 4]
 [3 4]
 [3 5]
 [4 2]
 [5 2]
 [5 5]]

and I want to replace the value of these indices in array A with :

zero=0

I want the final result to be something like this:

modified_A=    [[0.         0.         0.         0.         0.         0.        0.        ]

                [0.         1.98019867 1.96039735 1.90331502 1.81546888 1.70634771 0.      ]      

                [0.         2.         1.98019867 1.92311635 0.         1.72614904 0.      ]

                [0.         1.98019867 1.96039735 1.90331502 0.         0.         0.      ]

                [0.         1.92311635 0.         1.84623269 1.75838656 1.64926538 0.      ]

                [0.         1.83527021 0.        1.75838656 1.67054042 0.          0.      ]

                [0.         0.         0.         0.         0.         0.         0.      ]]

CodePudding user response:

You can use very terse notation like arr[ind] if you have ind as a tuple containing indices of consecutive "wanted" elements along consecutive axes.

To generate such a tuple from your index list, you can run:

ind = tuple(np.array(index).T)

The result is:

(array([1, 2, 3, 3, 4, 5, 5]), array([2, 4, 4, 5, 2, 2, 5]))

Then, to put 0 at wanted locations run:

arr[ind] = 0

For some random source array (with zeroes at all edges), like your source data sample, I got:

array([[0.    , 0.    , 0.    , 0.    , 0.    , 0.    , 0.    ],
       [0.    , 1.5488, 0.    , 1.6028, 1.5449, 1.4237, 0.    ],
       [0.    , 1.6459, 1.4376, 1.8918, 0.    , 1.3834, 0.    ],
       [0.    , 1.7917, 1.5289, 1.568 , 0.    , 0.    , 0.    ],
       [0.    , 1.0871, 0.    , 1.8326, 1.7782, 1.87  , 0.    ],
       [0.    , 1.9786, 0.    , 1.4615, 1.7805, 0.    , 0.    ],
       [0.    , 0.    , 0.    , 0.    , 0.    , 0.    , 0.    ]])

Values of each non-zero element are not important. Notice only that your "wanted" elements have been set to 0.

  • Related