如何基于numpy数组rel的抽取结果生成对应eta_extract数组?
eta_extract from rel, eta, and rel_extract First, let's break down the core relationship we're working with:
- Every element in
etamaps one-to-one with the positions of 0s in the originalrelarray, following the order those 0s appear inrel. rel_extractis a subset ofrelelements, so we need to trace the 0s inrel_extractback to their original positions inrel, then link those positions to the corresponding values ineta.
Critical Note
To make this mapping accurate, you must know the indices from the original rel that were used to create rel_extract (let's call this extract_indices). Without this, we can't definitively match 0s in rel_extract to their eta values—since multiple 0s in rel look identical in the subset.
Step-by-Step Implementation
Let's use your example data to walk through the code:
import numpy as np # Original datasets rel = np.array([1,0,0,1,1,0,1,0,1,0,0]) eta = np.array([2,3,10,16,4,3]) rel_extract = np.array([1,0,0,1,0]) # Replace this with your actual extraction indices (the positions pulled from rel to make rel_extract) extract_indices = np.array([0,1,2,3,9]) # This gives rel[extract_indices] = rel_extract
Capture all positions of 0s in the original
rel
This creates an ordered list where each index directly corresponds to an element ineta:zero_indices = np.where(rel == 0)[0] # Result: array([ 1, 2, 5, 7, 9, 10])Find original
relindices that map to 0s inrel_extract
Filterextract_indicesto keep only positions whererel_extracthas a 0:zero_extract_original_indices = extract_indices[rel_extract == 0] # Result: array([1, 2, 9])Map these original indices to their positions in
zero_indices
Sincezero_indicesis sorted (fromnp.where), we can usenp.searchsortedfor fast lookup:eta_positions = np.searchsorted(zero_indices, zero_extract_original_indices) # Result: array([0, 1, 4])Generate
eta_extractby indexing intoetaeta_extract = eta[eta_positions] # Final result: array([2, 3, 3])
Concise One-Liner Version
You can combine steps for brevity without losing clarity:
zero_indices = np.where(rel == 0)[0] eta_extract = eta[np.searchsorted(zero_indices, extract_indices[rel_extract == 0])]
What If You Don't Have extract_indices?
If you didn't record the indices used to create rel_extract, you'll need to infer them by matching element sequences—but this is unreliable if rel has repeated patterns. For example, you could use np.where to find all positions in rel that match the rel_extract sequence, but this only works for unique or contiguous subsets. Always track extract_indices when creating rel_extract for best results!
内容的提问来源于stack exchange,提问作者user23299

