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

วิธีเข้าถึงข้อมูลใน Series ด้วย Indexing ต่างๆ ใน Pandas Python

Pandas Series รองรับการเข้าถึงข้อมูลหลายรูปแบบ ทั้ง Positional Indexing (Integer) และ Label-based Indexing (Custom Index)

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


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)

print("The second element (zero-based indexing)")
print(my_series[2])

print("Elements from 2 to the last element are")
print(my_series[2:])

ผลลัพธ์


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

The second element (zero-based indexing)
78

Elements from 2 to the last element are
gh    78
kl    90
wq    123
az    45
dtype: int64

คำอธิบาย

  • สร้าง Series พร้อม Custom Index

  • my_series[2] - เข้าถึงด้วย Position (Integer Index) ได้ Element ที่ 3 (Index 2) = 78

  • my_series[2:] - Slicing ตั้งแต่ Position 2 ถึงสุดท้าย

ประเภท Indexing ใน Pandas Series

ประเภทSyntaxคำอธิบาย
Positionals.iloc[i]เข้าถึงตามตำแหน่ง (0-based) - แนะนำใช้ .iloc
Label-baseds.loc['label']เข้าถึงตาม Label Index - แนะนำใช้ .loc
Mixed (Legacy)s[key]ทำงานได้ทั้ง 2 แบบ แต่อาจสับสน (Deprecated behavior)

แนวทางปฏิบัติที่ดี (Best Practice)


# ชัดเจนและปลอดภัย
print(my_series.iloc[2])      # Position 2
print(my_series.loc['gh'])    # Label 'gh'
print(my_series.iloc[2:])     # Position 2 ถึงสุด
print(my_series.loc['gh':])   # Label 'gh' ถึงสุด

# Boolean Indexing
print(my_series[my_series > 50])  # ค่ามากกว่า 50

หมายเหตุ: ควรใช้ .iloc และ .loc แทน Bracket Notation โดยตรง เพื่อความชัดเจนและหลีกเลี่ยง Bug เมื่อ Index เป็น Integer