CodexBloom - Programming Q&A Platform

How to effectively use np.unique to count occurrences of elements in a 2D NumPy array while preserving the original shape?

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

I keep running into I'm working on a personal project and I tried several approaches but none seem to work. I'm trying to count the occurrences of each unique element in a 2D NumPy array and return the results as a 2D array that retains the original shape. I'm using NumPy version 1.24.0. I initially tried using `np.unique` with the `return_counts=True` parameter, but I ended up with a 1D array of counts that doesn't match the original dimensions of my data. Here's a sample of the code I've been working with: ```python import numpy as np data = np.array([[1, 2, 2], [3, 1, 1], [2, 3, 3]]) unique_elements, counts = np.unique(data, return_counts=True) print("Unique elements:", unique_elements) print("Counts:", counts) ``` This code correctly identifies the unique elements and their counts, but I want to create a new 2D array where each element indicates how many times that specific value appears in the original array. For instance, given the `data` array above, I would like to get an output that looks something like this: ``` [[2, 3, 3], [3, 2, 2], [3, 3, 3]] ``` I've tried reshaping the counts array but it doesn't align with the original indices of the numbers in `data` since it doesn't account for repetitions correctly. Is there a straightforward way to achieve this while ensuring that performance remains optimal, especially with larger datasets? Any help or guidance on how to tackle this would be greatly appreciated! How would you solve this? How would you solve this? I'm using Python LTS in this project. Any feedback is welcome!