如何根据指定索引过滤形状为(50000,32,32,3)的n维数组A生成新数组B
Hey there! Since your array A has a shape of (50000, 32, 32, 3), it’s clear the first dimension represents individual samples (each being a 32x32 RGB image). Grabbing only the samples at your specified indices is super straightforward with NumPy’s advanced indexing.
Here’s how you do it:
- First, make sure your target indices are stored as a NumPy array (a regular Python list works too). Let’s call this index collection
target_indices(like the array you provided:array([5, 10, 15, ..., 49988])). - Then, simply index your original array
Ausing this index array:
import numpy as np # Assuming A is your original array and target_indices is your index array B = A[target_indices]
This will create a new array B where each element corresponds to the slice of A at the indices in target_indices. The shape of B will be (len(target_indices), 32, 32, 3)—exactly what you need!
A quick note: This works because NumPy allows integer array indexing, which lets you pick out specific elements along a dimension. If you ever needed to index a different dimension (say, the second one), you’d adjust the indexing to A[:, target_indices], but based on your question, the first dimension is clearly the one you’re targeting.
内容的提问来源于stack exchange,提问作者Manasi

