วิธีนับค่าที่ไม่ซ้ำโดยใช้ pandas groupby
คุณสามารถใช้ไวยากรณ์พื้นฐานต่อไปนี้เพื่อนับจำนวนค่าที่ไม่ซ้ำกันต่อกลุ่มใน Pandas DataFrame:
df. groupby (' group_column ')[' count_column ']. nunique ()
ตัวอย่างต่อไปนี้แสดงวิธีการใช้ไวยากรณ์นี้กับ DataFrame ต่อไปนี้:
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'], ' position ': ['G', 'G', 'G', 'F', 'F', 'G', 'G', 'F', 'F', 'F'], ' points ': [5, 7, 7, 9, 12, 9, 9, 4, 7, 7], ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12, 13, 15]}) #view DataFrame df team position points rebounds 0 A G 5 11 1 A G 7 8 2 A G 7 10 3 A F 9 6 4 A F 12 6 5 B G 9 5 6 B G 9 9 7 B F 4 12 8 B F 7 13 9 B F 7 15
ตัวอย่างที่ 1: จัดกลุ่มตามคอลัมน์และนับค่าที่ไม่ซ้ำ
รหัสต่อไปนี้แสดงวิธีนับจำนวนค่าที่ไม่ซ้ำในคอลัมน์ “คะแนน” สำหรับแต่ละทีม:
#count number of unique values in 'points' column grouped by 'team' column
df. groupby (' team ')[' points ']. nunique ()
team
At 4
B 3
Name: points, dtype: int64
จากผลลัพธ์เราจะเห็นได้ว่า:
- มีค่า “คะแนน” ที่ไม่ซ้ำกัน 4 ค่าสำหรับทีม A
- มีค่า “คะแนน” ที่ไม่ซ้ำกัน 3 ค่าสำหรับทีม B
โปรดทราบว่าเรายังสามารถใช้ฟังก์ชัน Unique() เพื่อแสดงค่า “คะแนน” ที่ไม่ซ้ำกันแต่ละค่าต่อทีม:
#display unique values in 'points' column grouped by 'team'
df. groupby (' team ')[' points ']. single ()
team
A [5, 7, 9, 12]
B [9, 4, 7]
Name: points, dtype: object
ตัวอย่างที่ 2: จัดกลุ่มตามหลายคอลัมน์และนับค่าที่ไม่ซ้ำ
รหัสต่อไปนี้แสดงวิธีนับจำนวนค่าที่ไม่ซ้ำในคอลัมน์ “คะแนน” โดยจัดกลุ่มตามทีม และ ตำแหน่ง:
#count number of unique values in 'points' column grouped by 'team' and 'position'
df. groupby ([' team ', ' position '])[' points ']. nunique ()
team position
AF2
G2
BF 2
G 1
Name: points, dtype: int64
จากผลลัพธ์เราจะเห็นได้ว่า:
- มีค่า “คะแนน” ที่ไม่ซ้ำกัน 2 ค่าสำหรับผู้เล่นในตำแหน่ง “F” ในทีม A
- มีค่า “คะแนน” ที่ไม่ซ้ำกัน 2 ค่าสำหรับผู้เล่นในตำแหน่ง “G” ในทีม A
- มีค่า “คะแนน” ที่ไม่ซ้ำกัน 2 ค่าสำหรับผู้เล่นในตำแหน่ง “F” ในทีม B
- มีค่า “คะแนน” ที่ไม่ซ้ำกัน 1 ค่าสำหรับผู้เล่นในตำแหน่ง “G” ในทีม B
ขอย้ำอีกครั้งว่าเราสามารถใช้ฟังก์ชัน Unique() เพื่อแสดงค่า “คะแนน” ที่ไม่ซ้ำกันแต่ละค่าต่อทีมและต่อตำแหน่ง:
#display unique values in 'points' column grouped by 'team' and 'position'
df. groupby ([' team ', ' position '])[' points ']. single ()
team position
AF [9, 12]
G [5, 7]
BF [4, 7]
G [9]
Name: points, dtype: object
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีดำเนินการทั่วไปอื่น ๆ ในแพนด้า:
Pandas: วิธีค้นหาค่าที่ไม่ซ้ำในคอลัมน์
Pandas: วิธีค้นหาค่าที่ไม่ซ้ำในหลายคอลัมน์
Pandas: วิธีนับการเกิดขึ้นของค่าเฉพาะในคอลัมน์