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

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

ในการนับจำนวนค่าที่ไม่ซ้ำ (unique values) ในดัชนี (Index) ให้ใช้เมธอด index.value_counts() ใน 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("\nGet the count of unique values...\n", index.value_counts())

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

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("\nGet the count of unique values...\n", index.value_counts())

ผลลัพธ์

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
Get the count of unique values...
50    2
110   2
90    2
10    1
70    1
30    1
dtype: int64

คำอธิบาย

value_counts() คืนค่า Series ที่มีค่าที่ไม่ซ้ำเป็นดัชนี และจำนวนครั้งที่ปรากฏเป็นค่า เรียงจากมากไปน้อย (ค่าเริ่มต้น) 50, 110, 90 ปรากฏ 2 ครั้ง อื่นๆ 1 ครั้ง