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

Python – นับ Distinct Values ใน Pandas Aggregation ด้วย Numpy

ภาพรวม

ใช้ groupby().agg() ร่วมกับ pd.Series.nunique (distinct count) และ np.sum เพื่อสรุปข้อมูล

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


import pandas as pd
import numpy as np

dataFrame = pd.DataFrame({
    "Car": ['BMW', 'Audi', 'BMW', 'Lexus', 'Lexus'],
    "Place": ['Delhi', 'Bangalore', 'Delhi', 'Chandigarh', 'Chandigarh'],
    "Units": [100, 150, 50, 110, 90]
})

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

# Group by Car, aggregate: sum(Units), nunique(Place)
dataFrame = dataFrame.groupby("Car").agg({
    "Units": np.sum,
    "Place": pd.Series.nunique
})

print("\nUpdated DataFrame ...\n", dataFrame)

ผลลัพธ์

DataFrame ...
     Car       Place  Units
0    BMW     Delhi    100
1   Audi  Bangalore    150
2    BMW     Delhi     50
3  Lexus Chandigarh    110
4  Lexus Chandigarh     90

Updated DataFrame ...
       Units  Place
Car
Audi     150      1
BMW      150      1
Lexus    200      1

คำอธิบาย

  • BMW: Units=100+50=150, Place unique={'Delhi'} -> 1
  • Audi: Units=150, Place unique={'Bangalore'} -> 1
  • Lexus: Units=110+90=200, Place unique={'Chandigarh'} -> 1

Syntax แบบใหม่ (Pandas 1.0+)


# ใช้ Named Aggregation (อ่านง่ายกว่า)
result = dataFrame.groupby("Car").agg(
    Total_Units=("Units", "sum"),
    Unique_Places=("Place", "nunique")
)

ฟังก์ชัน Aggregation อื่นๆ

  • 'sum', 'mean', 'median', 'std', 'var'
  • 'min', 'max', 'first', 'last'
  • 'count', 'size', 'nunique'
  • Custom function: ('col', lambda x: x.max() - x.min())