Tim Leathart - 3 months ago 18

Python Question

I have an array:

`arr = np.array([[ 5.1, 3.5, 1.4, 0.2],`

[ 4.6, 3.1, 1.5, 0.2],

[ 5. , 3.6, 1.4, 0.2]])

and an index array:

`index_arr = np.array([True, False, False, True, True])`

and an empty matrix of zeros:

`output = np.array([[ 0., 0., 0., 0.],`

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

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

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

[ 0., 0., 0., 0.]])

Is there a way that I can combine these using numpy functions/indexing tricks such that the rows of my array replace the rows in the zero matrix according to the index array? That is, I would end up with this as my final output

`>>> array([[ 5.1, 3.5, 1.4, 0.2],`

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

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

[ 4.6, 3.1, 1.5, 0.2],

[ 5. , 3.6, 1.4, 0.2]])

If it's not clear what I want to do here: the two middle rows of the output are empty because the second and third entry in

`index_arr`

`False`

`arr`

`arr`

`True`

`index_arr`

Answer

You can use logical vector indexing for subsetting and assignment:

```
output[index_arr] = arr
#array([[ 5.1, 3.5, 1.4, 0.2],
# [ 0. , 0. , 0. , 0. ],
# [ 0. , 0. , 0. , 0. ],
# [ 4.6, 3.1, 1.5, 0.2],
# [ 5. , 3.6, 1.4, 0.2]])
```