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

Assign value to subset of numpy array

Given the following array:

x = np.zeros((1, 5))
x
# array([[0., 0., 0., 0., 0.]])

I’d like to be able to create array([[0., 3., 1., 0., 8.]]) using something such as:

values = [3, 1, 8]
indices = [1, 2, 4]
y = x.iloc[indices] = values

I appreciate that this doesn’t work – but I’m not sure what an idiomatic approach to this sort of thing in numpy would be.

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

The following works, but it doesn’t seem like it’s a sensible approach using numpy:

values = [3, 1, 8]
indices = [1, 2, 4]
for i, v in zip(indices, values):
    row[i] = v

>Solution :

Just move the indexer to the second position (because you’re modifying values in the second dimension):

x[:, indices] = values

Output:

>>> x
array([[0., 3., 1., 0., 8.]])
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