Home > Net >  How can I use numpy array elements as indices to assign values for another numpy array
How can I use numpy array elements as indices to assign values for another numpy array

Time:01-14

I have following problem, which I want to solve using numpy array elements. The problem is:

Matrix = np.zeros((4*4), dtype = bool) which gives this 2D matrix.

Matrix = [[False, False, False, False],
          [False, False, False, False],
          [False, False, False, False],
          [False, False, False, False]]

Les us suppose that we have an another array a = np.array([0,1], [2,1], [3,3])

a = [[0, 1], 
     [2, 1],
     [3, 3]]      

My question is: How to use the elements of the a array as indices to fill my matrix with True's. The output should seem like this

Matrix = [[False, True,  False, False], # [0, 1]
          [False, False, False, False],
          [False, True,  False, False], # [2, 1]
          [False, False, False, True]]  # [3, 3]

CodePudding user response:

import numpy as np
Matrix = np.zeros((4*4), dtype = bool).reshape(4,4)

a = [[0, 1], 
     [2, 1],
     [3, 3]]

Unroll them into a proper pair of indexing arrays for a 2d array

a = ([x[0] for x in a], [x[1] for x in a])
Matrix[a] = True

>>> Matrix
array([[False,  True, False, False],
       [False, False, False, False],
       [False,  True, False, False],
       [False, False, False,  True]])

CodePudding user response:

Simple way to make the (4,4) bool array:

In [390]: arr = np.zeros((4,4), dtype = bool)
In [391]: arr
Out[391]: 
array([[False, False, False, False],
       [False, False, False, False],
       [False, False, False, False],
       [False, False, False, False]])

Proper syntax for making a:

In [392]: a = np.array([[0,1], [2,1], [3,3]])
In [393]: a
Out[393]: 
array([[0, 1],
       [2, 1],
       [3, 3]])

Use the 2 columns of a as indices for the 2 dimensions of arr:

In [394]: arr[a[:,0],a[:,1]]=True
In [395]: arr
Out[395]: 
array([[False,  True, False, False],
       [False, False, False, False],
       [False,  True, False, False],
       [False, False, False,  True]])
  •  Tags:  
  • Related