Rumah  >  Artikel  >  pembangunan bahagian belakang  >  Bagaimana Mengira Nilai Unik setiap Kumpulan dengan Panda?

Bagaimana Mengira Nilai Unik setiap Kumpulan dengan Panda?

Susan Sarandon
Susan Sarandonasal
2024-10-18 15:49:03922semak imbas

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>

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

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>

Example with agg():

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

Atas ialah kandungan terperinci Bagaimana Mengira Nilai Unik setiap Kumpulan dengan Panda?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn