Để trả về Series chứa số lượng các giá trị duy nhất trong Index (mặc định sắp xếp giảm dần, bỏ qua NaN), hãy sử dụng phương thức index.value_counts().
Các bước thực hiện
1. Import thư viện cần thiết
import pandas as pd
2. Tạo Index
index = pd.Index([50, 10, 70, 110, 90, 50, 110, 90, 30])
3. Hiển thị Index
print("Pandas Index...\n", index)
4. Đếm giá trị duy nhất (mặc định)
print("\nĐếm giá trị duy nhất...\n", index.value_counts())
Ví dụ hoàn chỉnh
import pandas as pd
# Tạo Index
index = pd.Index([50, 10, 70, 110, 90, 50, 110, 90, 30])
# Hiển thị Index
print("Pandas Index...\n", index)
# Số lượng phần tử
print("\nSố phần tử (size)...\n", index.size)
# Kiểu dữ liệu
print("\nKiểu dữ liệu (dtype)...\n", index.dtype)
# Đếm giá trị duy nhất (mặc định)
print("\nĐếm giá trị duy nhất...\n", index.value_counts())
Kết quả đầu ra
Pandas Index...
Int64Index([50, 10, 70, 110, 90, 50, 110, 90, 30], dtype='int64')
Số phần tử (size)...
9
Kiểu dữ liệu (dtype)...
int64
Đếm giá trị duy nhất...
50 2
110 2
90 2
10 1
70 1
30 1
dtype: int64
Giải thích: Mặc định: dropna=True (bỏ NaN), ascending=False (giảm dần), (count tuyệt đối). 50,110,90 xuất hiện 2 lần (top), 10,70,30 xuất hiện 1 lần. Hữu ích cho EDA (Exploratory Data Analysis).