Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Numpy exercise
  • pandas
  • Matplotlib
  • Data visulisation
  • EDA
  • Machin Learning
  • Deep Learning
  • NLP
  • Data science
  • ML Tutorial
  • Computer Vision
  • ML project
Open In App
Next Article:
NumPy| How to get the unique elements of an Array
Next article icon

How to count the frequency of unique values in NumPy array?

Last Updated : 02 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Let’s see How to count the frequency of unique values in the NumPy array. Python’s Numpy library provides a numpy.unique() function to find the unique elements and their corresponding frequency in a NumPy array.

numpy.unique() Syntax

Syntax: numpy.unique(arr, return_counts=False)

Return: Sorted unique elements of an array with their corresponding frequency counts NumPy array.

Get Unique Items and Counts in Numpy Array

There are various ways to get unique items and counts in the Numpy array here we explain some generally used methods for getting unique items and counts in the Numpy array those are following.

  • Using the np.unique() Function
  • Using NumPy Unique Frequency
  • Using NumPy in Transpose Form
  • Using numpy.bincount()
  • Using the collections.Counter() Function

Using the np.unique() Function

In this example code uses NumPy to create an array (`ini_array`) and then utilizes `np.unique()` to obtain unique values and their frequencies. The unique values are printed with “Unique Values:”, and their corresponding frequencies are printed with “Frequency Values:”.

Python3




# import library
import numpy as np
 
ini_array = np.array([10, 20, 5,
                      10, 8, 20,
                      8, 9])
 
# Get a tuple of unique values
# and their frequency in
# numpy array
unique, frequency = np.unique(ini_array,
                              return_counts = True)
# print unique values array
print("Unique Values:",
      unique)
 
# print frequency array
print("Frequency Values:",
      frequency)
 
 

Output:

Unique Values: [ 5  8  9 10 20]
Frequency Values: [1 2 1 2 2]

Using NumPy Unique Frequency

In this example code, utilizing NumPy, generates a 1D array (`ini_array`) and then employs `np.unique()` to obtain unique values and their frequencies. The results are combined into a single NumPy array (`count`) and printed, displaying the values and their frequencies.

Python3




# import library
import numpy as np
 
# create a 1d-array
ini_array = np.array([10, 20, 5,
                    10, 8, 20,
                    8, 9])
 
# Get a tuple of unique values
# and their frequency
# in numpy array
unique, frequency = np.unique(ini_array,
                              return_counts = True)
 
# convert both into one numpy array
count = np.asarray((unique, frequency ))
 
print("The values and their frequency are:\n",
     count)
 
 

Output:

The values and their frequency are:
[[ 5 8 9 10 20]
[ 1 2 1 2 2]]

Using NumPy in Transporse Form

In this example code uses NumPy to create a 1D array (`ini_array`) and employs `np.unique()` to obtain unique values and their frequencies. The results are combined into a NumPy array (`count`), which is then transposed for a display of values and frequencies in a transposed form.

Python3




# import library
import numpy as np
 
# create a 1d-array
ini_array = np.array([10, 20, 5,
                      10, 8, 20,
                      8, 9])
 
# Get a tuple of unique values
# and their frequency in
# numpy array
unique, frequency = np.unique(ini_array,
                              return_counts = True)
 
# convert both into one numpy array
# and then transpose it
count = np.asarray((unique,frequency )).T
 
print("The values and their frequency are in transpose form:\n",
     count)
 
 

Output:

The values and their frequency are in transpose form:
[[ 5 1]
[ 8 2]
[ 9 1]
[10 2]
[20 2]]

Using numpy.bincount() Function

In this example, a 1D NumPy array `arr` is created with integer values. Using `numpy.unique()`, unique values and their counts are obtained. The results are displayed, showcasing the unique values and their corresponding counts using the `numpy.bincount()` method, ensuring proper alignment with the unique values.

Python3




import numpy as np
 
# Create a 1D array
arr = np.array([10, 20, 5, 10, 8, 20, 8, 9])
 
# Get unique values and their counts using bincount
unique_values = np.unique(arr)
counts = np.bincount(arr)
 
# Display the results
print("\nMethod 2:")
print("Unique Values:", unique_values)
print("Counts:", counts[unique_values])
 
 

Output:

Unique Values: [ 5  8  9 10 20]
Counts: [1 2 1 2 2]

Using the collections.Counter() Function

In this example The code employs `Counter` from the `collections` module to count occurrences of elements in the list `my_list`. It then prints the unique values and their respective counts, offering a concise summary of the element frequencies in the list.

Python3




from collections import Counter
 
# Create a list
my_list = [10, 20, 5, 10, 8, 20, 8, 9]
 
# Use Counter to count occurrences
counts = Counter(my_list)
 
# Display the results
print("Unique Values:", list(counts.keys()))
print("Counts:", list(counts.values()))
 
 

Output:

Unique Values: [10, 20, 5, 8, 9]
Counts: [2, 2, 1, 2, 1]



Next Article
NumPy| How to get the unique elements of an Array
author
viv_007
Improve
Article Tags :
  • Python
  • Python numpy-Matrix Function
  • Python-numpy
Practice Tags :
  • python

Similar Reads

  • How to find the Index of value in Numpy Array ?
    In this article, we are going to find the index of the elements present in a Numpy array. Using where() Methodwhere() method is used to specify the index of a particular element specified in the condition. Syntax: numpy.where(condition[, x, y]) Example 1: Get index positions of a given valueHere, we
    5 min read
  • NumPy| How to get the unique elements of an Array
    To find unique elements of an array we use the numpy.unique() method of the NumPy library in Python. It returns unique elements in a new sorted array. Example: C/C++ Code import numpy as np arr = np.array([1, 2, 3, 1, 4, 5, 2, 5]) unique_elements = np.unique(arr) print(unique_elements) Output: [1 2
    2 min read
  • How to count unique values in a Pandas Groupby object?
    Here, we can count the unique values in Pandas groupby object using different methods. This article depicts how the count of unique values of some attribute in a data frame can be retrieved using Pandas. Method 1: Count unique values using nunique() The Pandas dataframe.nunique() function returns a
    3 min read
  • Find the most frequent value in a NumPy array
    In this article, let's discuss how to find the most frequent value in the NumPy array. Steps to find the most frequency value in a NumPy array: Create a NumPy array.Apply bincount() method of NumPy to get the count of occurrences of each element in the array.The n, apply argmax() method to get the v
    1 min read
  • How to Create Frequency Tables in Python?
    In this article, we are going to see how to Create Frequency Tables in Python Frequency is a count of the number of occurrences a particular value occurs or appears in our data. A frequency table displays a set of values along with the frequency with which they appear. They allow us to better unders
    3 min read
  • Calculate the frequency counts of each unique value of a Pandas series
    Let us see how to find the frequency counts of each unique value of a Pandas series. We will use these methods to calculate the frequency counts of each unique value of a Pandas series. Using values_counts() to calculate the frequency of unique value Here values_counts() function is used to find the
    2 min read
  • How to Calculate the Mode of NumPy Array?
    The goal here is to calculate the mode of a NumPy array, which refers to identifying the most frequent value in the array. For example, given the array [1, 1, 2, 2, 2, 3, 4, 5], the mode is 2, as it appears most frequently. Let's explore different approaches to accomplish this. Using scipy.stats.mod
    2 min read
  • Python - Frequencies of Values in a Dictionary
    Sometimes, while working with python dictionaries, we can have a problem in which we need to extract the frequency of values in the dictionary. This is quite a common problem and has applications in many domains including web development and day-day programming. Let's discuss certain ways in which t
    4 min read
  • Counting Frequency of Values by Date in Pandas
    Counting the frequency of values by date is a common task in time-series analysis, where we need to analyze how often certain events occur within specific time frames. Understanding these frequencies can provide valuable insights if we analyze sales data, website traffic, or any other date-related d
    3 min read
  • Find common values between two NumPy arrays
    In this article, we are going to discuss how to find out the common values between 2 arrays. To find the common values, we can use the numpy.intersect1d(), which will do the intersection operation and return the common values between the 2 arrays in sorted order. Syntax: numpy.intersect1d(arr1, arr2
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences