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

Python Pandas - หาค่าที่ไม่ซ้ำในดัชนี (index.unique)

ในการหาค่าที่ไม่ซ้ำ (unique values) ในดัชนี (Index) ให้ใช้เมธอด index.unique() ใน Pandas

ขั้นตอนการทำงาน

1. นำเข้าไลบรารีที่จำเป็น

import pandas as pd

2. สร้างดัชนี

index = pd.Index([10, 50, 70, 10, 90, 50, 10, 30])

3. แสดงดัชนี

print("Pandas Index...\n", index)

4. หาค่าที่ไม่ซ้ำ

index.unique()

ตัวอย่างโค้ดสมบูรณ์

import pandas as pd

# สร้างดัชนี
index = pd.Index([10, 50, 70, 10, 90, 50, 10, 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())

ผลลัพธ์

Pandas Index... Int64Index([10, 50, 70, 10, 90, 50, 10, 30], dtype='int64')
Number of elements in the index... 8
The dtype object... int64
Unique values from the Index.. Int64Index([10, 50, 70, 90, 30], dtype='int64')

คำอธิบาย

unique() คืนค่าดัชนีใหม่ที่มีเฉพาะค่าที่ไม่ซ้ำ ตามลำดับที่ปรากฏครั้งแรก (ไม่ได้เรียงลำดับ) 10 ปรากฏก่อน 50 แล้ว 70, 90, 30