CodexBloom - Programming Q&A Platform

np.unique not preserving order when used with return_index on 1D array

👀 Views: 1 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-11
numpy np.unique data-manipulation Python

I'm having an scenario with the `np.unique` function in NumPy version 1.24.0. I'm trying to extract unique values from a 1D array while also retaining their original order using the `return_index` parameter. However, I noticed that the order of the unique values returned does not match the order in which they appear in the original array. Here's the code I'm using: ```python import numpy as np array = np.array([3, 1, 2, 3, 2, 1]) unique_values, indices = np.unique(array, return_index=True) print(f'Unique values: {unique_values}') # Expected: [3, 1, 2] print(f'Indices: {indices}') # Expected: indices corresponding to [3, 1, 2] ``` When I run this, I get: ``` Unique values: [1 2 3] Indices: [1 2 0] ``` It seems like `np.unique` is sorting the unique values by default and therefore returning an array that does not preserve the original order. I've also checked the documentation and it doesn't specify that `return_index` affects the ordering of the output. Is there a way to get the unique values while preserving their order from the original array? I've tried different combinations and even looked into `np.unique` with the `return_inverse` parameter, but that just complicates things further. Any help would be appreciated! My development environment is Ubuntu. Thanks in advance!