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!
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.]])
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With