Pandas: วิธีกรองแถวตามความยาวของสตริง
คุณสามารถใช้วิธีการต่อไปนี้เพื่อกรองแถวที่ประกอบด้วยสตริงที่มีความยาวเฉพาะใน DataFrame ของแพนด้า:
วิธีที่ 1: กรองแถวตามความยาวของสตริงในคอลัมน์
#filter rows where col1 has a string length of 5 df. loc [df[' col1 ']. str . len () == 5 ]
วิธีที่ 2: กรองแถวตามความยาวสตริงของหลาย คอลัมน์
#filter rows where col1 has string length of 5 and col2 has string length of 7 df. loc [(df[' col1 ']. str . len () == 5 ) & (df[' col2 ']. str . len () == 7 )]
ตัวอย่างต่อไปนี้แสดงวิธีการใช้แต่ละวิธีในทางปฏิบัติกับ Pandas DataFrame ต่อไปนี้:
import pandas as pd #createDataFrame df = pd. DataFrame ({' conf ': ['East', 'East', 'North', 'West', 'North', 'South'], ' pos ': ['Guard', 'Guard', 'Forward', 'Center', 'Center', 'Forward'], ' points ': [5, 7, 7, 9, 12, 9]}) #view DataFrame print (df) conf pos points 0 East Guard 5 1 East Guard 7 2 North Forward 7 3 West Center 9 4 North Center 12 5 South Forward 9
ตัวอย่างที่ 1: กรองแถวตามความยาวสตริงในคอลัมน์
รหัสต่อไปนี้แสดงวิธีการกรองแถวจาก DataFrame ที่มีความยาวสตริง 5 ในคอลัมน์ conf :
#filter rows where conf has a string length of 5 df. loc [df[' conf ']. str . len () == 5 ] conf pos points 2 North Forward 7 4 North Center 12 5 South Forward 9
เฉพาะแถวที่คอลัมน์ conf มีความยาวสตริง 5 เท่านั้นที่จะถูกส่งกลับ
เราจะเห็นว่าสตริงที่แตกต่างกันสองรายการตรงตามเกณฑ์นี้ในคอลัมน์ conf :
- “ทิศเหนือ”
- “ใต้”
ทั้งสองสายมีความยาว 5
ตัวอย่างที่ 2: กรองแถวตามความยาวสตริงของหลายคอลัมน์
รหัสต่อไปนี้แสดงวิธีการกรองแถวจาก DataFrame ที่มีความยาวสตริง 5 ในคอลัมน์ conf และความยาวสตริง 7 ในคอลัมน์ pos :
#filter rows where conf has string length of 5 and pos has string length of 7 df. loc [(df[' conf ']. str . len () == 5 ) & (df[' pos ']. str . len () == 7 )] conf pos points 2 North Forward 7 5 South Forward 9
เฉพาะแถวที่คอลัมน์ conf มีความยาวสตริง 5 และคอลัมน์ pos มีความยาวบังคับ 7 เท่านั้นที่จะถูกส่งกลับ
หมายเหตุ : คุณสามารถดูเอกสารฉบับเต็มของฟังก์ชัน str.len() ใน pandas ได้ที่นี่
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีดำเนินการทั่วไปอื่น ๆ ในแพนด้า:
วิธีลบแถวใน Pandas DataFrame ตามเงื่อนไข
วิธีกรอง Pandas DataFrame ในหลายเงื่อนไข
วิธีใช้ตัวกรอง “NOT IN” ใน Pandas DataFrame