Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Đếm số lượng bản ghi theo nhóm (Designation) DataFrame Python pandas

Giả sử bạn có DataFrame nhân viên và muốn đếm số lượng theo từng Chức danh (Designation).

Giải pháp

  • Tạo DataFrame.
  • Nhóm và đếm: df.groupby('Designation').count().

Mã ví dụ

import pandas as pd

data = {
    'Id': [1,2,3,4,5],
    'Designation': ['architect', 'scientist', 'programmer', 'scientist', 'programmer']
}
df = pd.DataFrame(data)

print("DataFrame:\n", df)
print("\nĐếm theo Designation:\n", df.groupby('Designation').count())

Kết quả

DataFrame:
   Id  Designation
0   1   architect
1   2   scientist
2   3  programmer
3   4   scientist
4   5  programmer

Đếm theo Designation:
             Id
Designation
architect      1
programmer     2
scientist      2

Giải thích:

  • groupby('Designation') nhóm theo cột Designation.
  • .count() đếm số giá trị không null của các cột còn lại (ở đây chỉ có 'Id').
  • Có thể dùng .size() để đếm số hàng (bao gồm NaN).
  • Đếm cột cụ thể: df.groupby('Designation')['Id'].count().