Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

นับจำนวนแถวในแต่ละกลุ่มของ DataFrame ด้วย groupby() และ count()

ใช้ groupby() จัดกลุ่มข้อมูลตามคอลัมน์หมวดหมู่ แล้วตามด้วย count() เพื่อนับจำนวนแถว (observations) ในแต่ละกลุ่ม สำหรับทุกคอลัมน์ที่ไม่ใช่คอลัมน์กลุ่ม

ตัวอย่างโค้ด

import pandas as pd

df = pd.DataFrame({
    'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone'],
    'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Electronics', 'Computer', 'Mobile Phone'],
    'Quantity': [10, 50, 10, 20, 25, 50]
})

print("DataFrame:\n", df)

# จัดกลุ่มตาม Product Category แล้วนับ
grouped = df.groupby("Product Category").count()
print("\nจำนวนแถวในแต่ละกลุ่ม:\n", grouped)

ผลลัพธ์

DataFrame:
    Product Name Product Category  Quantity
0      Keyboard         Computer        10
1       Charger     Mobile Phone        50
2       SmartTV      Electronics        10
3        Camera      Electronics        20
4  Graphic Card         Computer        25
5      Earphone     Mobile Phone        50

จำนวนแถวในแต่ละกลุ่ม:
                Product Name  Quantity
Product Category
Computer                 2         2
Electronics              2         2
Mobile Phone             2         2

แต่ละหมวดหมู่มี 2 แถว (2 สินค้า) คอลัมน์ Quantity ก็มี 2 ค่าในแต่ละกลุ่ม