Return the sorted distinct values of a NumPy array and their counts
Quick Overview
Write a NumPy function that returns the distinct values of a 1-D array in ascending order together with how many times each one occurs. It tests NumPy's built-in set routines, sort-based counting and edge cases such as empty input and NaN values.
Return the sorted distinct values of a NumPy array and their counts
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: easy
Interview Round: Other
Given a 1-D NumPy array, return a tuple of two NumPy arrays `(values, counts)`: `values` holds the distinct elements in ascending order and `counts[i]` is the number of occurrences of `values[i]`.
For example:
```python
a = np.array([3, 1, 2, 3, 3, 1])
values, counts = solve(a)
# values -> array([1, 2, 3])
# counts -> array([2, 1, 3])
```
```hint Start from the sort
Once the array is sorted, equal elements sit next to each other. Look at what NumPy's set routines can return besides the distinct values.
```
### What a Strong Answer Covers
- A working function that returns two aligned NumPy arrays, with `values` in ascending order.
- Why `counts[i]` is guaranteed to belong to `values[i]`, and the cost of the sort the method relies on.
- How the function behaves on an empty array, a multi-dimensional input and NaN values.
- A way to get the same result without the one-call shortcut, such as sorting and measuring the runs of equal values.
### Follow-up Questions
- Which single NumPy call gives you this directly?
- How would you also get the index that maps each element back to `values`?
- When is `np.bincount` a better choice than a sort, and when does it fail?
- How does `pandas.Series.value_counts` differ from the output this task asks for?
Overview: Write a NumPy function that returns the distinct values of a 1-D array in ascending order together with how many times each one occurs. It tests NumPy's built-in set routines, sort-based counting and edge cases such as empty input and NaN values.
Given a 1-D NumPy array, return a tuple of two NumPy arrays (values, counts): values holds the distinct elements in ascending order and counts[i] is the number of occurrences of values[i].