简体   繁体   中英

Python numpy assigning values to a 2D array using another array with ordered pairs as indices to the 2D array

This is hard to describe in words but easy to see in practice. I have a 2D array:

im = np.array([[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]])

I'm interpreting it as a 4x4 grayscale image - so the values in the array are simply intensities. So, to start with, im is:

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

I want to be able to change many values in the "image" at once according to an array of x values and an array of y values. I assemble them to look like ordered pairs in a second array like this:

x = [0,1]
y = [2,3]
coords = np.array([x,y]).T

Now coords looks like this:

array([[0, 2],
       [1, 3]])

Finally, I want to index im by coords. I thought perhaps it was something like this:

im[coords] = 9

...but that doesn't work. I'd like the final result of im to be:

[[0,0,9,0],
 [0,0,0,9],
 [0,0,0,0],
 [0,0,0,0]]

Does anyone know of a fast and elegant way of doing this?

Thanks!

In general, if you have a numpy array

import numpy as np
arr = np.array([[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]])
x_coords = [0, 1]
y_coords = [2, 3]
values = [8, 9]

then

arr[x, y] = values

will result in

  array([
        [0, 0, 8, 0],
        [0, 0, 0, 9],
        [0, 0, 0, 0],
        [0, 0, 0, 0]
        ])

You can simply do im[x,y] = 9 .

ex:

im = np.array([[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]])
x = [0,1]
y = [2,3]
im[x,y] = 9
print(im)
# Result:
# array([[0, 0, 9, 0],
#        [0, 0, 0, 9],
#        [0, 0, 0, 0],
#        [0, 0, 0, 0]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM