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

Boolean Indexing ใน Pandas

Boolean Indexing ใน Pandas ใช้เลือกข้อมูลจาก DataFrame ด้วย Boolean Vector (True/False) ช่วยกรองแถวได้อย่างมีประสิทธิภาพ

สร้าง DataFrame พร้อม Boolean Index

import pandas as pd

data = {
    'Name': ['Hafeez', 'Srikanth', 'Rakesh'],
    'Age': [19, 20, 19]
}

# สร้าง DataFrame กำหนด index เป็น boolean
df = pd.DataFrame(data, index=[True, False, True])
print(df)

ผลลัพธ์

       Name  Age
True   Hafeez   19
False  Srikanth  20
True   Rakesh    19

เข้าถึงข้อมูลด้วย .loc[]

print(df.loc[True])
      Name  Age
True  Hafeez   19
True  Rakesh   19

เข้าถึงด้วย .iloc[]

.iloc[] รับ integer เท่านั้น True=1, False=0

print(df.iloc[1])  # แถว index 1 (False)
Name    Srikanth
Age            20
dtype: object

เข้าถึงด้วย .ix[] (Deprecated)

.ix[] รองรับทั้ง boolean และ integer (Deprecated ใน Pandas ใหม่)

Boolean Vector โดยตรงกับ DataFrame

ส่ง boolean list เข้า DataFrame โดยตรง (ไม่ต้องตั้ง index)

df = pd.DataFrame(data)  # index เป็น 0,1,2
print(df[[True, True, False]])
     Name  Age
0  Hafeez   19
1  Srikanth 20

สรุป: ใช้ df.loc[boolean_mask] หรือ df[boolean_mask] สำหรับ Pandas เวอร์ชันใหม่ ไม่ควรใช้ .ix[]