วิธีลบแถวใน pandas dataframe ตามเงื่อนไข
เราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อลบแถวใน DataFrame ของแพนด้าตามเงื่อนไข:
วิธีที่ 1: ลบแถวตามเงื่อนไขเดียว
df = df[df. col1 > 8]
วิธีที่ 2: ลบแถวตามเงื่อนไขหลายข้อ
df = df[(df. col1 > 8) & (df. col2 != ' A ')]
หมายเหตุ : เรายังสามารถใช้ฟังก์ชัน drop() เพื่อปล่อยแถวจาก DataFrame ได้ แต่ฟังก์ชันนี้ได้รับการพิสูจน์แล้วว่าช้ากว่าการกำหนด DataFrame ให้กับเวอร์ชันที่กรองของตัวเองมาก
ตัวอย่างต่อไปนี้แสดงวิธีการใช้ไวยากรณ์นี้ในทางปฏิบัติกับ Pandas DataFrame ต่อไปนี้:
import pandas as pd #createDataFrame df = pd. DataFrame ({' team ': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'], ' pos ': ['G', 'G', 'F', 'F', 'G', 'G', 'F', 'F'], ' assists ': [5, 7, 7, 9, 12, 9, 9, 4], ' rebounds ': [11, 8, 10, 6, 6, 5, 9, 12]}) #view DataFrame df team pos assists rebounds 0 A G 5 11 1 A G 7 8 2 A F 7 10 3 A F 9 6 4 B G 12 6 5 B G 9 5 6 B F 9 9 7 B F 4 12
วิธีที่ 1: ลบแถวตามเงื่อนไขเดียว
รหัสต่อไปนี้แสดงวิธีการลบแถวใน DataFrame ตามเงื่อนไข:
#drop rows where value in 'assists' column is less than or equal to 8
df = df[df. assists > 8]
#view updated DataFrame
df
team pos assists rebounds
3 A F 9 6
4 B G 12 6
5 B G 9 5
6 B F 9 9
แถวใด ๆ ที่มีค่าน้อยกว่าหรือเท่ากับ 8 ในคอลัมน์ “ความช่วยเหลือ” จะถูกลบออกจาก DataFrame
วิธีที่ 2: ลบแถวตามเงื่อนไขหลายข้อ
รหัสต่อไปนี้แสดงวิธีการลบแถวใน DataFrame ตามเงื่อนไขหลายประการ:
#only keep rows where 'assists' is greater than 8 and rebounds is greater than 5
df = df[(df. assists > 8) & (df. rebounds > 5)]
#view updated DataFrame
df
team pos assists rebounds
3 A F 9 6
4 B G 12 6
5 B G 9 5
6 B F 9 9
แถวเดียวที่เราเก็บไว้ใน DataFrame คือแถวที่มีค่า Assists มากกว่า 8 และ ค่า Rebounds มากกว่า 5
โปรดทราบว่าเรายังสามารถใช้ | โอเปอเรเตอร์เพื่อใช้ตัวกรอง “หรือ”:
#only keep rows where 'assists' is greater than 8 or rebounds is greater than 10
df = df[(df. assists > 8) | (df. rebounds > 10)]
#view updated DataFrame
df
team pos assists rebounds
0 A G 5 11
3 A F 9 6
4 B G 12 6
5 B G 9 5
6 B F 9 9
7 B F 4 12
แถวเดียวที่เราเก็บไว้ใน DataFrame คือแถวที่มีค่าช่วยเหลือมากกว่า 8 หรือ ค่าการฟื้นตัวมากกว่า 10
แถวที่ไม่ตรงตามเงื่อนไขข้อใดข้อหนึ่งเหล่านี้จะถูกลบออก
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีดำเนินการทั่วไปอื่น ๆ ในแพนด้า:
วิธีลบแถวที่มีค่าเฉพาะใน Pandas
วิธีลบแถวที่มีสตริงเฉพาะใน Pandas
วิธีลบแถวตามดัชนีใน Pandas