Wie zähle ich mit Pandas eindeutige Werte pro Gruppe?

Susan Sarandon
Freigeben: 2024-10-18 15:49:03
Original
921 Leute haben es durchsucht

How to Count Unique Values per Groups with Pandas?

Counting Unique Values per Groups with Pandas

When working with tabular data, it often becomes necessary to count the unique occurrences of values within specific groups. To achieve this in Python using the Pandas library, we can utilize the groupby() and nunique() methods.

Problem Explanation:

To illustrate the problem, consider the following dataset:

ID domain
123 vk.com
123 vk.com
123 twitter.com
456 vk.com'
456 facebook.com
456 vk.com
456 google.com
789 twitter.com
789 vk.com

The task at hand is to count the unique ID values within each domain.

Solution:

To count unique values per group, we can use the following code:

<code class="python">df = df.groupby('domain')['ID'].nunique()</code>
Nach dem Login kopieren

The groupby() method groups the data by the domain column, while the nunique() method counts the unique occurrences of ID within each group. The output is a Series with the domain names as index and the corresponding unique counts as values.

domain
vk.com        3
twitter.com   2
facebook.com  1
google.com    1
Nach dem Login kopieren

Additional Notes:

  • If the domain column values contain single quotes ('), you can remove them before grouping using the str.strip("'") method.
  • To retain the column name in the output, use the agg() method with the pd.Series.nunique function.

Example with String Manipulation:

<code class="python">df['clean_domain'] = df.domain.str.strip("'")
df = df.groupby('clean_domain')['ID'].nunique()</code>
Nach dem Login kopieren

Example with agg():

<code class="python">df = df.groupby(by='domain', as_index=False).agg({'ID': pd.Series.nunique})</code>
Nach dem Login kopieren

Das obige ist der detaillierte Inhalt vonWie zähle ich mit Pandas eindeutige Werte pro Gruppe?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:php
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Artikel des Autors
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!