Pandas: เลือกแถวจาก dataframe โดยใช้ชุดบูลีน
คุณสามารถใช้ไวยากรณ์พื้นฐานต่อไปนี้เพื่อเลือกแถวใน DataFrame แพนด้าตามค่าของชุดบูลีน:
#define boolean series bools = pd. Series ([ True , False , True , True , False , False , False , True ]) #select rows in DataFrame based on values in boolean series df[bools. values ]
ซึ่งช่วยให้คุณสามารถเลือกแต่ละแถวใน Pandas DataFrame โดยที่ค่าที่สอดคล้องกันในชุดบูลีนคือ True
ตัวอย่างต่อไปนี้แสดงวิธีใช้ไวยากรณ์นี้ในทางปฏิบัติ
ตัวอย่าง: เลือกแถวใน Pandas DataFrame โดยใช้ชุดบูลีน
สมมติว่าเรามี DataFrame แพนด้าต่อไปนี้ซึ่งมีข้อมูลเกี่ยวกับผู้เล่นบาสเกตบอลต่างๆ:
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], ' points ': [18, 22, 19, 14, 14, 11, 20, 28], ' assists ': [5, 7, 7, 9, 12, 9, 9, 4], ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]}) #view DataFrame print (df) team points assists rebounds 0 A 18 5 11 1 B 22 7 8 2 C 19 7 10 3 D 14 9 6 4 E 14 12 6 5 F 11 9 5 6 G 20 9 9 7:28 4 12
เราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อเลือกแถวทั้งหมดใน DataFrame โดยที่ค่าที่สอดคล้องกันในชุดบูลีนเป็น True :
#define boolean series bools = pd. Series ([ True , False , True , True , False , False , False , True ]) #select rows in DataFrame based on values in boolean series df[bools. values ] team points assists rebounds 0 A 18 5 11 2 C 19 7 10 3 D 14 9 6 7:28 4 12
โปรดทราบว่าแถวเดียวที่ส่งคืนคือแถวที่มีค่าที่สอดคล้องกันในชุดบูลีนเป็น True
โปรดทราบว่าคุณสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อเลือกเฉพาะแถวในคอลัมน์ “points” ของ DataFrame โดยที่ ค่าที่สอดคล้องกันในชุดบูลีนคือ True
#define boolean series bools = pd. Series ([ True , False , True , True , False , False , False , True ]) #select rows in points column based on values in boolean series df[' points '][bools. values ] 0 18 2 19 3 14 7 28 Name: points, dtype: int64
โปรดทราบว่าแถวเดียวที่ส่งคืนโดยคอลัมน์ “points” คือแถวที่มีค่าที่สอดคล้องกันในชุดบูลีนเป็น True
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีการทำงานทั่วไปอื่นๆ ในแพนด้า:
วิธีกรองแถวตามความยาวสตริงใน Pandas
วิธีเลือกแถวที่ไม่มีค่า NaN ใน Pandas
วิธีเลือกแถวตามค่าคอลัมน์ใน Pandas