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

วิธีเข้าถึง Top N Elements ของ Series ใน Pandas Python

ใน Pandas Series สามารถใช้ Slicing ด้วย Operator : เพื่อดึงข้อมูลช่วงที่ต้องการ เช่น Top N Elements

ตัวอย่างโค้ด


import pandas as pd

my_data = [34, 56, 78, 90, 123, 45]
my_index = ['ab', 'mn', 'gh', 'kl', 'wq', 'az']
my_series = pd.Series(my_data, index=my_index)

print("The series contains following elements")
print(my_series)

n = 3
print("Top 3 elements are :")
print(my_series[:n])

ผลลัพธ์


The series contains following elements
ab    34
mn    56
gh    78
kl    90
wq    123
az    45
dtype: int64

Top 3 elements are :
ab    34
mn    56
gh    78
dtype: int64

คำอธิบาย

  • สร้าง Series ด้วยข้อมูลและ Custom Index

  • ใช้ Slicing my_series[:n] โดย n=3

  • Slicing [:n] หมายถึง เริ่มต้นที่ 0 ถึง n-1 (ไม่รวม n)

  • แสดง 3 แถวแรก ตามลำดับ Index

กฎ Slicing ใน Pandas

Syntaxความหมาย
series[:n]Top N Elements (Index 0 ถึง n-1)
series[n:]Elements ตั้งแต่ Index n ถึงสุดท้าย
series[m:n]Elements Index m ถึง n-1
series[-n:]Last N Elements
series[::2]ทุก 2 Elements (Step=2)

การเรียงลำดับก่อนดึง Top N

หากต้องการ Top N ตามค่า (Value) ไม่ใช่ลำดับ Index:


# Top 3 ค่ามากที่สุด
top3 = my_series.nlargest(3)
print(top3)

# Bottom 3 ค่าน้อยที่สุด
bottom3 = my_series.nsmallest(3)
print(bottom3)

ผลลัพธ์ nlargest(3): wq=123, kl=90, gh=78