Home > Back-end >  Get Numpy ndarray value from list of nd points
Get Numpy ndarray value from list of nd points

Time:03-08

How can I obtain value of a ndarray from a list that contains coordinates of a n-D point as efficient as possible.

Here an implementation for 3D :

1    arr = np.array([[[0, 1]]])
2    points = [[0, 0, 1], [0, 0, 0]]
3    values = []
4    for point in points:
5        x, y, z = point
6        value.append(arr[x, y, z])
7     # values -> [1, 0]

If this is not possible, is there a way to generalize lines 5-6 to nD?

CodePudding user response:

I am sure there is way to achieve this using fancy indexing. Here is a way to do without the for-loop:

arr = np.array([[[0, 1]]])
points = np.array([[0, 0, 1], [0, 0, 0]])
x,y,z = np.split(points, 3, axis=1)
arr[x,y,z]

output (values):

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

Alternatively, you could use tuple unpacking as suggested by the comment:

arr[(*points.T,)]

output:

array([1, 0])

CodePudding user response:

Based on the Numpy documentation for indexing, you can easily do that, as long as you use tuples instead of lists:

arr = np.array([[[0, 1]]])
points = [(0, 0, 1), (0, 0, 0)]
values = []
for point in points:
    value.append(arr[point])

# values -> [1, 0]

This works independent of dimensionality of the Numpy array involved.

Bonus: In addition to appending to a list, you can also use the Python slice function to extract ranges directly:

arr = np.array([[[0, 1]]])
points = (0, 0, slice(2) )

vals = arr[points]
# --> [0 1] (a Numpy array!)
  • Related