วิธีเชื่อมต่อ pandas dataframes สองตัวเข้าด้วยกัน (พร้อมตัวอย่าง)
คุณสามารถใช้ไวยากรณ์พื้นฐานต่อไปนี้เพื่อเชื่อม DataFrames แพนด้าสองตัวเข้าด้วยกัน:
df3 = pd. concat ([df1, df2], ignore_index= True )
ตัวอย่างต่อไปนี้แสดงวิธีใช้ไวยากรณ์นี้ในทางปฏิบัติ
ตัวอย่าง: วิธีเชื่อมต่อ Pandas DataFrames สองตัวเข้าด้วยกัน
สมมติว่าเรามี DataFrames แพนด้าสองตัวต่อไปนี้:
import pandas as pd #define DataFrames df1 = pd. DataFrame ({' team ': ['A', 'A', 'A', 'A'], ' assists ': [5, 7, 7, 9], ' points ': [11, 8, 10, 6]}) df2 = pd. DataFrame ({' team ': ['B', 'B', 'B', 'B'], ' assists ': [4, 4, 3, 7], ' points ': [14, 11, 7, 6]}) #view DataFrames print (df1) team assists points 0 to 5 11 1 to 7 8 2 to 7 10 3 to 9 6 print (df2) team assists points 0 B 4 14 1 B 4 11 2 B 3 7 3 B 7 6
เราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อเชื่อม DataFrames ทั้งสองเข้าด้วยกัน:
#concatenate the DataFrames
df3 = pd. concat ([df1, df2])
#view resulting DataFrame
print (df3)
team assists points
0 to 5 11
1 to 7 8
2 to 7 10
3 to 9 6
0 B 4 14
1 B 4 11
2 B 3 7
3 B 7 6
ผลลัพธ์ที่ได้คือ DataFrame ที่มีข้อมูลจาก DataFrames ทั้งสอง
หากคุณต้องการสร้างดัชนีใหม่เมื่อเชื่อมต่อ DataFrames คุณต้องใช้อาร์กิวเมนต์ ign_index :
#concatenate the DataFrames and ignore index
df3 = pd. concat ([df1, df2], ignore_index= True )
#view resulting DataFrame
print (df3)
team assists points
0 to 5 11
1 to 7 8
2 to 7 10
3 to 9 6
4 B 4 14
5 B 4 11
6 B 3 7
7 B 7 6
โปรดทราบว่าดัชนีของ DataFrame ที่เป็นผลลัพธ์อยู่ระหว่าง 0 ถึง 7
หมายเหตุ #1: ในตัวอย่างนี้ เราได้ต่อ DataFrames แพนด้าสองตัวเข้าด้วยกัน แต่คุณสามารถใช้ไวยากรณ์ที่ตรงกันทุกประการนี้เพื่อเชื่อม DataFrames จำนวนเท่าใดก็ได้ที่คุณต้องการ
หมายเหตุ #2: คุณสามารถค้นหาเอกสารฉบับเต็มสำหรับฟังก์ชัน pandas concat() ได้ ที่นี่
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีดำเนินการทั่วไปอื่น ๆ ในแพนด้า:
วิธีผสาน Pandas DataFrames ในหลายคอลัมน์
วิธีรวม Pandas DataFrames สองตัวบนดัชนี
วิธีเพิ่มคอลัมน์ใน Pandas DataFrame