Pandas: วิธีเลือกคอลัมน์ตามการจับคู่บางส่วน
คุณสามารถใช้วิธีการต่อไปนี้เพื่อเลือกคอลัมน์ใน Pandas DataFrame ตามการจับคู่บางส่วน:
วิธีที่ 1: เลือกคอลัมน์ตามการจับคู่บางส่วน
#select columns that contain 'team'
df. loc [:, df. columns . str . contains (' team ')]
วิธีที่ 2: เลือกคอลัมน์ตามการจับคู่บางส่วนหลายรายการ
#select columns that contain 'team' or 'rebounds'
df. loc [:, df. columns . str . contains (' team|rebounds ')]
ตัวอย่างต่อไปนี้แสดงวิธีการใช้แต่ละวิธีกับ DataFrame แพนด้าต่อไปนี้:
import pandas as pd #createDataFrame df = pd. DataFrame ({' team_name ': ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'], ' team_points ': [5, 7, 7, 9, 12, 9, 9, 4], ' assists ': [11, 8, 10, 6, 6, 5, 9, 12], ' rebounds ': [6, 7, 7, 6, 10, 12, 10, 9]}) #view DataFrame print (df) team_name team_points assists rebounds 0 A 5 11 6 1 To 7 8 7 2 To 7 10 7 3 to 9 6 6 4 B 12 6 10 5 B 9 5 12 6 B 9 9 10 7 B 4 12 9
ตัวอย่างที่ 1: เลือกคอลัมน์ตามการจับคู่บางส่วน
รหัสต่อไปนี้แสดงวิธีการเลือกคอลัมน์ทั้งหมดใน DataFrame แพนด้าที่มี “ทีม” ในชื่อคอลัมน์:
#select columns that contain 'team'
df_team_cols = df. loc [:, df. columns . str . contains (' team ')]
#view results
print (df_team_cols)
team_name team_points
0 to 5
1 to 7
2 to 7
3 to 9
4 B 12
5 B 9
6 B 9
7 B 4
โปรดทราบว่าทั้งสองคอลัมน์ที่มี “ทีม” ในชื่อจะถูกส่งกลับ
ตัวอย่างที่ 2: เลือกคอลัมน์ตามการจับคู่บางส่วนหลายรายการ
รหัสต่อไปนี้แสดงวิธีการเลือกคอลัมน์ทั้งหมดใน DataFrame แพนด้าที่มี “ทีม” หรือ “ตีกลับ” ในชื่อคอลัมน์:
#select columns that contain 'team' or 'rebounds'
df_team_rebs = df. loc [:, df. columns . str . contains (' team|rebounds ')]
#view results
print (df_team_rebs)
team_name team_points rebounds
0 to 5 6
1 To 7 7
2 to 7 7
3 to 9 6
4 B 12 10
5 B 9 12
6 B 9 10
7 B 4 9
คอลัมน์ทั้งหมดที่มีชื่อ “ทีม” หรือ “รีบาวด์” จะถูกส่งกลับ
หมายเหตุ : | ตัวดำเนินการแทน “OR” ในหมีแพนด้า
คุณสามารถใช้โอเปอเรเตอร์เหล่านี้ได้มากเท่าที่คุณต้องการเพื่อค้นหาการจับคู่สตริงบางส่วนได้มากเท่าที่คุณต้องการ
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีดำเนินการทั่วไปอื่น ๆ ในแพนด้า:
วิธีเลือกคอลัมน์ตามชื่อใน Pandas
วิธีเลือกคอลัมน์ตามดัชนีใน Pandas
วิธีเลือกคอลัมน์ตามประเภทข้อมูลใน Pandas