How to Query Distinct Count in Pandas Using \'nunique()\'?

Linda Hamilton
Release: 2024-10-23 13:43:02
Original
233 people have browsed it

How to Query Distinct Count in Pandas Using 'nunique()'?

Querying Distinct Count in Pandas Using 'nunique()'

To perform a count of distinct values in Pandas, similar to the 'count(distinct)' function in SQL, use the 'nunique()' method.

The syntax for 'nunique()' is:

dataframe.groupby(groupby_column).column_to_count.nunique()
Copy after login

Example:

To count the distinct clients per year in a Pandas DataFrame named 'table':

table.groupby('YEARMONTH').CLIENTCODE.nunique()
Copy after login

Explanation:

  • table.groupby('YEARMONTH') groups the DataFrame by the 'YEARMONTH' column.
  • CLIENTCODE selects the column to count distinct values.
  • nunique() returns the number of distinct values in 'CLIENTCODE' for each group.

Output:

The output of the query will be a series with the 'YEARMONTH' as the index and the count of distinct 'CLIENTCODE' values as the values.

YEARMONTH
201301       2
201302       3
Copy after login

The above is the detailed content of How to Query Distinct Count in Pandas Using \'nunique()\'?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!