Unique Values and Counts Practice Problem
This data science coding problem helps you practice Array Manipulation, unique values and counts, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Array Manipulation.
- Problem ID: 63
- Problem key: 63-unique-values-and-counts
- URL: https://datacrack.app/solve/63-unique-values-and-counts
- Difficulty: easy
- Topic: Array Manipulation
- Module: NumPy Foundations
Problem Statement
# 🧩 Unique Values and Counts
---
### 🎯 Goal
Finding unique values and their frequencies is a foundational EDA operation. It answers: "What categories exist in my data? How many times does each appear?" This is the NumPy equivalent of `value_counts()` in Pandas and the building block of class distribution analysis in ML.
---
### 🔍 `np.unique` with `return_counts`
```python
arr = np.array([1, 2, 2, 3, 3, 3])
values, counts = np.unique(arr, return_counts=True)
# values → [1, 2, 3]
# counts → [1, 2, 3]
```
`np.unique` returns unique values in sorted order. For numeric arrays, this means ascending order.
---
### 💻 Task
Implement `unique_with_counts(data)` using `np.unique()`.
---
### 📥 Input
- `data`: list of numbers (may contain duplicates)
### 📤 Output
- dict with keys:
- `"unique"`: sorted list of unique values
- `"counts"`: list of counts corresponding to each unique value
---
### 🧩 Starter Code
```python
import numpy as np
def unique_with_counts(data):
"""
Find unique values and their occurrence counts.
Args:
data (list): Input numbers with possible duplicates
Returns:
dict: {"unique": [...], "counts": [...]}
"""
arr = np.array(data)
# 🧠 TODO
pass
```
---
### 💡 Example
```python
unique_with_counts([1, 2, 2, 3, 3, 3, 4, 4, 4, 4])
# Expected: {"unique": [1, 2, 3, 4], "counts": [1, 2, 3, 4]}
```
---
### 🔑 Key Concepts
- `np.unique(arr)` — unique values in sorted order
- `np.unique(arr, return_counts=True)` — also returns how many times each appears
- Class imbalance check: `counts / counts.sum()` gives class proportionsStarter Code
import numpy as np
def unique_with_counts(data):
"""
Find unique values and their occurrence counts.
Args:
data (list): Input numbers with possible duplicates
Returns:
dict: {"unique": [...], "counts": [...]}
"""
arr = np.array(data)
# 🧠 TODO
pass