ในการนับจำนวนค่าที่ไม่ซ้ำ (unique values) ในดัชนี (Index) รวมถึงค่า NaN ให้ใช้เมธอด index.value_counts() พร้อมตั้งค่าพารามิเตอร์ dropna=False
ขั้นตอนการทำงาน
1. นำเข้าไลบรารีที่จำเป็น
import pandas as pd
import numpy as np
2. สร้างดัชนีที่มี NaN
index = pd.Index([50, 10, 70, np.nan, 90, 50, np.nan, np.nan, 30])
3. แสดงดัชนี
print("Pandas Index...\n", index)
4. นับค่าที่ไม่ซ้ำรวม NaN
index.value_counts(dropna=False)
ตัวอย่างโค้ดสมบูรณ์
import pandas as pd
import numpy as np
# สร้างดัชนีที่มี NaN
index = pd.Index([50, 10, 70, np.nan, 90, 50, np.nan, np.nan, 30])
# แสดงดัชนี
print("Pandas Index...\n", index)
# แสดงจำนวนองค์ประกอบ
print("\nNumber of elements in the index...\n", index.size)
# แสดง dtype ของข้อมูล
print("\nThe dtype object...\n", index.dtype)
# นับค่าที่ไม่ซ้ำรวม NaN
print("\nGet the count of unique values with NaN...\n", index.value_counts(dropna=False))
ผลลัพธ์
Pandas Index... Float64Index([50.0, 10.0, 70.0, nan, 90.0, 50.0, nan, nan, 30.0], dtype='float64')
Number of elements in the index... 9
The dtype object... float64
Get the count of unique values with NaN...
NaN 3
50.0 2
10.0 1
70.0 1
90.0 1
30.0 1
dtype: int64
คำอธิบาย
dropna=False ทำให้นับ NaN เป็นค่าหนึ่งค่า (ปรากฏ 3 ครั้ง) ค่าเริ่มต้น dropna=True จะไม่นับ NaN