Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Turning list of indices into numpy array

I have an nxd numpy array of zeros. For every row in this array, I am tasked with converting a specified column to be a 1. To this end, I have been given a list of size n such that the ith value of this list is the index to be turned into a 1.

This task can be accomplished via a for loop as below:

import numpy as np

N=5; D =3
array = np.zeros(shape=(N,D))
ones_index = [0,2,1,0,1]
for row, column in enumerate(ones_index):
    array[row,column] = 1

While this works just fine, I imagine that numpy has some function to achieve this above much more cleanly. Does there exist a numpy function that converts a list of indices into a certain values in an array?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One possible solution:

array = np.zeros(shape=(N, D))

ones_index = [0, 2, 1, 0, 1]
array[np.arange(N), ones_index] = 1

print(array)

Prints:

[[1. 0. 0.]
 [0. 0. 1.]
 [0. 1. 0.]
 [1. 0. 0.]
 [0. 1. 0.]]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading