CodexBloom - Programming Q&A Platform

np.where not returning expected indices in a 3D array operation with NumPy 1.24

๐Ÿ‘€ Views: 0 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-16
numpy indexing 3D-array Python

I'm experimenting with I'm building a feature where I tried several approaches but none seem to work..... I've encountered an scenario while trying to use `np.where` to extract indices from a 3D numpy array based on a condition. I have a 3D array representing a grid of data points, and I want to find the indices where the values exceed a certain threshold. However, the output is not what I expected. Hereโ€™s the relevant part of my code: ```python import numpy as np # Creating a 3D array of shape (4, 4, 4) data = np.random.rand(4, 4, 4) threshold = 0.5 # Trying to find indices where values exceed the threshold indices = np.where(data > threshold) print(indices) ``` The output for `print(data)` shows a grid with some values exceeding 0.5, but when I print `indices`, it returns three arrays, one for each dimension, containing the indices of the True values, which I am expecting. However, when I try to use these indices to access the elements in the original array, I am getting unexpected results: ```python # Attempting to retrieve the actual values using the indices selected_values = data[indices] print(selected_values) ``` Instead of getting the values that exceed the threshold, it's returning a flattened array of values that doesnโ€™t match with what I thought it should return. I want to ensure that I am correctly using the indices to extract the respective values from the original 3D array. Is there something Iโ€™m missing in the way I'm trying to fetch these values or in how `np.where` behaves with multi-dimensional arrays? Any insights would be greatly appreciated! This is part of a larger service I'm building. I'm open to any suggestions. I'm developing on Windows 10 with Python. Any feedback is welcome!