Index multiple elements in multidimensional numpy array

王林
Release: 2024-02-22 14:00:06
forward
984 people have browsed it

索引多维 numpy 数组中的多个元素

Question content

I want to extract the elements of a given multidimensional numpy array using another indexed array. But it doesn't behave as I expected. Here is a simple example:

import numpy as np

a = np.random.random((3, 3, 3))
idx = np.asarray([[0, 0, 0], [0, 1, 2]])

b = a[idx]
print(b.shape)  # expect (2, ), got (2, 3, 3, 3)
Copy after login

Why is this so? How should I modify the code so that b only contains two elements: a[0, 0, 0] and a[0, 1, 2]?


Correct answer


You are looking for numpy advanced indexing

https://www.php.cn/link/2d661a763280f48803f3c9ba8ba0e00b

In your case you need to use idx on each axis:

a[idx[:,0], idx[:, 1], idx[:, 2]].shape == (2,)  # True
Copy after login

The above is the detailed content of Index multiple elements in multidimensional numpy array. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!