ในการค้นหาองค์ประกอบทั่วไปใน Pandas DataFrame เราสามารถใช้เมธอด merge() กับรายการคอลัมน์
ขั้นตอน
-
สร้างข้อมูลตารางแบบสองมิติที่ปรับขนาดได้และอาจต่างกันได้ df1 .
-
พิมพ์ DataFrame อินพุต df1 .
-
สร้างข้อมูลตารางสองมิติอื่น df2 .
-
พิมพ์ DataFrame อินพุต df2 .
-
ค้นหาองค์ประกอบทั่วไปโดยใช้ merge() วิธีการ
-
พิมพ์ DataFrame ทั่วไป
ตัวอย่าง
import pandas as pd
df1 = pd.DataFrame(
{
"x": [5, 2, 7, 0],
"y": [4, 7, 5, 1],
"z": [9, 3, 5, 1]
}
)
df2 = pd.DataFrame(
{
"x": [5, 2, 7, 0, 11, 12],
"y": [4, 7, 5, 1, 19, 20],
"z": [9, 3, 5, 1, 29, 30]
}
)
print("Input DataFrame 1 is:\n", df1)
print("Input DataFrame 2 is:\n", df2)
common = df1.merge(df2, on=['x', 'y', 'z'])
print("Common of DataFrame 1 and 2 is: \n", common) ผลลัพธ์
Input DataFrame 1 is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 Input DataFrame 2 is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 4 11 19 29 5 12 20 30 Common of DataFrame 1 and 2 is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1