นุ่น: รับแถวที่ไม่ได้อยู่ใน dataframe อื่น
คุณสามารถใช้ไวยากรณ์พื้นฐานต่อไปนี้เพื่อรับแถวจาก Pandas DataFrame ที่ไม่ได้อยู่ใน DataFrame อื่น:
#merge two DataFrames and create indicator column df_all = df1. merge ( df2.drop_duplicates (), on=[' col1 ',' col2 '], how=' left ', indicator= True ) #create DataFrame with rows that exist in first DataFrame only df1_only = df_all[df_all[' _merge '] == ' left_only ']
ตัวอย่างต่อไปนี้แสดงวิธีใช้ไวยากรณ์นี้ในทางปฏิบัติ
ตัวอย่าง: การรับแถวใน Pandas DataFrame ที่ไม่ได้อยู่ใน DataFrame อื่น
สมมติว่าเรามี DataFrames แพนด้าสองตัวต่อไปนี้:
import pandas as pd #create first DataFrame df1 = pd. DataFrame ({' team ': ['A', 'B', 'C', 'D', 'E'], ' points ': [12, 15, 22, 29, 24]}) print (df1) team points 0 to 12 1 B 15 2 C 22 3 D 29 4 E 24 #create second DataFrame df2 = pd. DataFrame ({' team ': ['A', 'D', 'F', 'G', 'H'], ' points ': [12, 29, 15, 19, 10]}) print (df2) team points 0 to 12 1 D 29 2 F 15 3 G 19 4:10 a.m.
เราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อรวม DataFrame ทั้งสองเข้าด้วยกัน และสร้างคอลัมน์ตัวบ่งชี้เพื่อระบุว่าแถวใดเป็นของแต่ละ DataFrame:
#merge two DataFrames and create indicator column df_all = df1. merge ( df2.drop_duplicates (), on=[' team ',' points '], how=' left ', indicator= True ) #view result print (df_all)
จากนั้นเราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อรับเฉพาะแถวจาก DataFrame แรกที่ไม่อยู่ใน DataFrame ที่สอง:
#create DataFrame with rows that exist in first DataFrame only df1_only = df_all[df_all[' _merge '] == ' left_only '] #view DataFrame print (df1_only) team points _merge 1 B 15 left_only 2 C 22 left_only 4 E 24 left_only
สุดท้าย เราสามารถลบคอลัมน์ _merge ได้หากต้องการ:
#drop '_merge' column
df1_only = df1_only. drop (' _merge ', axis= 1 )
#view DataFrame
print (df1_only)
team points
1 B 15
2 C 22
4 E 24
ผลลัพธ์คือ DataFrame ซึ่งมีแถวทั้งหมดอยู่ใน DataFrame แรก แต่ไม่มีอยู่ใน DataFrame ที่สอง
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีการทำงานทั่วไปอื่นๆ ในแพนด้า:
วิธีเพิ่มคอลัมน์จาก DataFrame หนึ่งไปยังอีกคอลัมน์หนึ่งใน Pandas
วิธีเปลี่ยนลำดับคอลัมน์ใน Pandas
วิธีจัดเรียงคอลัมน์ตามชื่อใน Pandas