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

Python Pandas - นับค่าที่ไม่ซ้ำเรียงจากน้อยไปมาก (value_counts ascending=True)

ในการนับจำนวนค่าที่ไม่ซ้ำ (unique values) ในดัชนี (Index) และเรียงจากน้อยไปมาก (ascending) ให้ใช้เมธอด index.value_counts() พร้อมตั้งค่าพารามิเตอร์ ascending=True

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

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 sorted in ascending order...\n", index.value_counts(ascending=True))

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

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 sorted in ascending order...\n", index.value_counts(ascending=True))

ผลลัพธ์

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 sorted in ascending order...
10    1
70    1
30    1
50    2
110   2
90    2
dtype: int64

คำอธิบาย

ascending=True เรียงผลลัพธ์ตามจำนวนนับจากน้อยไปมาก ค่าเริ่มต้น ascending=False เรียงจากมากไปน้อย ค่าที่มีจำนวนเท่ากันจะเรียงตามลำดับค่า