ในการหาจำนวนค่าที่ไม่ซ้ำ (unique elements) ในดัชนี (Index) ให้ใช้เมธอด index.nunique() ใน Pandas
ขั้นตอนการทำงาน
1. นำเข้าไลบรารีที่จำเป็น
import pandas as pd
2. สร้างดัชนี
index = pd.Index([50, 10, 70, 110, 90, 50, 110, 90, 30])
3. แสดงดัชนี
print("Pandas Index...\n", index)
4. หาจำนวนค่าที่ไม่ซ้ำ
print("\nCount of unique values...\n", index.nunique())
ตัวอย่างโค้ดสมบูรณ์
import pandas as pd
# สร้างดัชนี
index = pd.Index([50, 10, 70, 110, 90, 50, 110, 90, 30])
# แสดงดัชนี
print("Pandas Index...\n", index)
# แสดงจำนวนองค์ประกอบ
print("\nNumber of elements in the index...\n", index.size)
# แสดง dtype ของข้อมูล
print("\nThe dtype object...\n", index.dtype)
# หาค่าที่ไม่ซ้ำ
print("\nUnique values from the Index..\n", index.unique())
# หาจำนวนค่าที่ไม่ซ้ำ
print("\nCount of unique values...\n", index.nunique())
ผลลัพธ์
Pandas Index... Int64Index([50, 10, 70, 110, 90, 50, 110, 90, 30], dtype='int64')
Number of elements in the index... 9
The dtype object... int64
Unique values from the Index.. Int64Index([50, 10, 70, 110, 90, 30], dtype='int64')
Count of unique values... 6
คำอธิบาย
nunique() คืนค่าจำนวนค่าที่ไม่ซ้ำ (6 ค่า: 50, 10, 70, 110, 90, 30) ไม่นับ NaN โดยค่าเริ่มต้น unique() คืนค่าดัชนีของค่าที่ไม่ซ้ำ ตามลำดับที่ปรากฏ