Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign values to different index positions in Numpy array

Say I have an array

np.zeros((4,2))

I have a list of values [4,3,2,1], which I want to assign to the following positions: [(0,0),(1,1),(2,1),(3,0)]

How can I do that without using the for loop or flattening the array?

I can use fancy index to retrieve the value, but not to assign them.

======Update=========

Thanks to @hpaulj, I realize the bug in my original code is.

When I use zeros_like to initiate the array, it defaults to int and truncates values. Therefore, it looks like I did not assign anything!

like image 362
Junchen Avatar asked Jan 27 '17 18:01

Junchen


2 Answers

You can use tuple indexing:

>>> import numpy as np
>>> a = np.zeros((4,2))
>>> vals = [4,3,2,1]
>>> pos = [(0,0),(1,1),(2,0),(3,1)]
>>> rows, cols = zip(*pos)
>>> a[rows, cols] = vals
>>> a
array([[ 4.,  0.],
       [ 0.,  3.],
       [ 2.,  0.],
       [ 0.,  1.]])
like image 150
wim Avatar answered Sep 21 '22 05:09

wim


Here is a streamlined version of @wim's answer based on @hpaulj's comment. np.transpose automatically converts the Python list of tuples into a NumPy array and transposes it. tuple casts the index coordinates to tuples which works because a[rows, cols] is equivalent to a[(rows, cols)] in NumPy.

import numpy as np
a = np.zeros((4, 2))
vals = range(4)
indices = [(0, 0), (1, 1), (2, 0), (3, 1)]
a[tuple(np.transpose(indices))] = vals
print(a)
like image 25
Robin Dinse Avatar answered Sep 20 '22 05:09

Robin Dinse