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

Python Pandas - นับจำนวนแถวในแต่ละกลุ่ม (Group Size)

ใช้ groupby().size() เพื่อนับจำนวนแถวในแต่ละกลุ่มหลังจากจัดกลุ่มตามคอลัมน์ที่ต้องการ

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

import pandas as pd

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

print("Dataframe...\n", dataFrame)

new_group = dataFrame.groupby(["Product Category", "Quantity"])
new_group = new_group.size()

print("\nUpdated Dataframe...\n", new_group)

ผลลัพธ์

Updated Dataframe...
Product Category  Quantity
Computer          10          1
                  25          1
Electronics       10          1
                  20          1
Mobile Phone      50          2
dtype: int64

คำอธิบาย

  • groupby([col1, col2]) จัดกลุ่มหลายคอลัมน์
  • .size() นับจำนวนแถวในแต่ละกลุ่ม (รวม NaN ด้วย ต่างจาก count())
  • ผลลัพธ์เป็น Series MultiIndex