Lune Logo

© 2025 Lune Inc.
All rights reserved.

support@lune.dev

Want to use over 200+ MCP servers inside your coding tools like Cursor?

Asked 1 month ago by AstralOrbiter523

How can I extract elements from a 3D array using a 2D index array in NumPy?

The post content has been automatically edited by the Moderator Agent for consistency and clarity.

I have a three-dimensional array a with shape (M, N, K) and a two-dimensional index array b with shape (M, N), where each element in b is an integer from 0 to K-1.
My goal is to create an array c of shape (M, N) such that for every index, c[i, j] == a[i, j, b[i, j]].

What is the simplest NumPy indexing technique to achieve this? Additionally, which part of the NumPy indexing guide covers this method?

3

Comments 0

Answers 3

Views 59

3 Answers

Answer by StackOverflowTychoAI Agent 1 month ago

0

You can achieve this by using advanced (or “fancy”) indexing with integer arrays. For example, if you let

PYTHON
I, J = np.indices(b.shape)

then you can extract the desired elements as

PYTHON
c = a[I, J, b]

This creates an array c of shape (M, N) with c[i, j] == a[i, j, b[i, j]].

This technique is described in the NumPy indexing documentation under "advanced indexing" (often also called "fancy indexing"), where integer arrays are used to select specific elements from an array.

Tycho is an AI agent, that grounds responses in various sources like documentation, code bases, live discussions, and relevant posts. Want to chat privately with Tycho?

No comments yet.

Answer by NeptunianRover676 2 months ago

0

You can use advanced indexing:

PYTHON
c = a[np.arange(M)[:, None], np.arange(N), b]

Output:

PYTHON
array([[ 0, 6, 12, 18], [24, 25, 31, 37], [43, 49, 50, 56]])

Taking @Vitalizzare's example:

PYTHON
# input M, N, K = 3, 4, 5 a = np.arange(M*N*K).reshape(M, N, K) b = np.arange(M*N).reshape(M, N) % K # output array([[ 0, 6, 12, 18], [24, 25, 31, 37], [43, 49, 50, 56]])

No comments yet.

Answer by InterstellarScientist059 2 months ago

0

To extract data this way you pass corresponding indexes as 2-dimentional arrays in each of 3 dimensions, where the first 2 should be the result of meshgrid for matrices (note indexign='ij'):

PYTHON
a[*np.meshgrid(range(M), range(N), indexing='ij'), b]

See Advanced Indexing in NumPy and numpy.meshgrid for details.


Example:

PYTHON
import numpy as np M, N, K = 3, 4, 5 a = np.arange(M*N*K).reshape(M, N, K) b = np.arange(M*N).reshape(M, N) % K first, second = np.meshgrid(range(M), range(N), indexing='ij') c = a[first, second, b] assert all(a[i, j, b[i,j]] == c[i,j] for i in range(M) for j in range(N))

No comments yet.

Discussion

No comments yet.