如何获取将数组B排序为数组A的索引?(NumPy场景)
Solution to Match Array B to Array A via Sort Indices
Got it, let's break this down. The issue with using np.argsort(B) directly is that it sorts B based on the natural lexicographical order of its elements, not the exact sequence defined by array A. Even if A happens to be in lex order, relying on that isn't reliable if you need to explicitly align to A's specific order.
Here's a solid, flexible way to get the indices that will reorder B to match A perfectly:
Step-by-Step Approach
- Create a position mapping from A: Build a dictionary that maps each element in A to its index position. This gives us a "rulebook" for how elements should be ordered to match A.
- Translate B using the mapping: Convert every element in B to its corresponding index from A. This turns the problem into sorting this new array into ascending order (0, 1, 2, ...).
- Use
np.argsorton the translated array: The resulting indices will rearrange the translated array into order, which directly translates to rearranging B to match A.
Code Example
import numpy as np A = np.array(['a', 'b', 'c', 'd']) B = np.array(['d', 'b', 'a', 'c']) # 1. Build element-to-index mapping from A element_to_a_pos = {val: idx for idx, val in enumerate(A)} # 2. Convert B elements to their positions in A ranked_b = np.array([element_to_a_pos[val] for val in B]) # 3. Get indices to sort ranked_b (and thus B) into A's order sort_indices = np.argsort(ranked_b) # Verify the result print("Reordered B:", B[sort_indices]) # Output: ['a' 'b' 'c' 'd'] (matches A) print("Required indices:", sort_indices) # Output: [2 1 3 0]
Why This Works
- The mapping ensures we're using A's sequence as the definitive sort key, not the elements' default order.
np.argsort(ranked_b)finds the positions that will arrangeranked_binto ascending order (0 to 3), which directly translates to arranging B into the exact order of A.
Edge Case Note
If A or B contain duplicate elements, you'll need to add logic to track element counts (e.g., using np.unique with return counts), but for your example with unique elements, this method works flawlessly.
内容的提问来源于stack exchange,提问作者Bradipo Eremita
相关产品推荐
相关产品推荐

