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

Boolean Indexing ใน Python (Pandas)

Boolean Indexing ใช้ค่า True/False (หรือ 1/0) เป็นดัชนีใน Pandas DataFrame เพื่อกรองแถวข้อมูล

สร้าง Boolean Index

import pandas as pd

game = {
    'Day': ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"],
    'points': [31, 24, 16, 11, 22]
}

df = pd.DataFrame(game, index=[True, False, True, False, True])
print(df)

ผลลัพธ์

       Day  points
True   Monday     31
False  Tuesday    24
True   Wednesday  16
False  Thursday   11
True   Friday     22

กรองด้วย .loc[]

print(df.loc[True])
       Day  points
True  Monday     31
True  Wednesday  16
True  Friday     22

ใช้ .ix[] กับ Integer (Deprecated)

df = pd.DataFrame(game, index=[1, 1, 0, 0, 1])
print(df.ix[0])
       Day  points
0  Wednesday    16
0  Thursday     11

หมายเหตุ: .ix[] ถูก Deprecated แล้วใน Pandas ใหม่ ควรใช้ .loc[] (label-based) หรือ .iloc[] (position-based) แทน

Boolean Mask แบบไม่ตั้ง Index

df = pd.DataFrame(game)  # Default index 0,1,2,3,4
mask = [True, True, False, False, True]
print(df[mask])