Pandas: วิธีเพิ่มคอลัมน์จาก dataframe หนึ่งไปยังอีก dataframe
คุณสามารถใช้หนึ่งในสองวิธีเพื่อเพิ่มคอลัมน์จาก Pandas DataFrame ไปยัง DataFrame อื่น:
วิธีที่ 1: เพิ่มคอลัมน์จาก DataFrame หนึ่งไปยังตำแหน่งคอลัมน์สุดท้ายในอีกคอลัมน์หนึ่ง
#add some_col from df2 to last column position in df1 df1[' some_col ']= df2[' some_col ']
วิธีที่ 2: เพิ่มคอลัมน์ของ DataFrame หนึ่งอันที่ตำแหน่งเฉพาะในอีกอันหนึ่ง
#insert some_col from df2 into third column position in df1 df1. insert ( 2 , ' some_col ', df2[' some_col '])
ตัวอย่างต่อไปนี้แสดงวิธีการใช้แต่ละวิธีในทางปฏิบัติกับ Pandas DataFrames ต่อไปนี้:
import pandas as pd #create first DataFrame df1 = pd. DataFrame ({'team': ['A', 'A', 'A', 'A', 'B', 'B'], 'position': ['G', 'G', 'F', 'C', 'G', 'C'], 'points': [4, 4, 6, 8, 9, 5]}) #view DataFrame print (df1) team position points 0 AG 4 1 GA 4 2 AF 6 3 AC 8 4 BG 9 5 BC 5 #create second DataFrame df2 = pd. DataFrame ({'team': ['A', 'A', 'A', 'A', 'B', 'B'], 'rebounds': [12, 7, 8, 8, 5, 11]}) #view DataFrame print (df2) team rebounds 0 to 12 1 to 7 2 to 8 3 to 8 4 B 5 5 B 11
ตัวอย่างที่ 1: เพิ่มคอลัมน์จาก DataFrame หนึ่งไปยังตำแหน่งคอลัมน์สุดท้ายในอีกคอลัมน์หนึ่ง
รหัสต่อไปนี้แสดงวิธีการเพิ่มคอลัมน์ ตีกลับ ของ DataFrame ที่สองไปยังตำแหน่งคอลัมน์สุดท้ายของ DataFrame แรก:
#add rebounds column from df2 to df1 df1[' rebounds ']= df2[' rebounds '] #view updated DataFrame print (df1) team position points rebounds 0 AG 4 12 1 GA 4 7 2 AF 6 8 3 AC 8 8 4 BG 9 5 5 BC 5 11
โปรดทราบว่าคอลัมน์ ตีกลับ ของ DataFrame ที่สองถูกเพิ่มไปยังตำแหน่งคอลัมน์สุดท้ายของ DataFrame แรก
ตัวอย่างที่ 2: เพิ่มคอลัมน์จาก DataFrame หนึ่งไปยังตำแหน่งคอลัมน์เฉพาะในอีกคอลัมน์หนึ่ง
รหัสต่อไปนี้แสดงวิธีการเพิ่มคอลัมน์ ตีกลับ ของ DataFrame ที่สองไปยังตำแหน่งคอลัมน์ที่สามของ DataFrame แรก:
#insert rebounds column from df2 into third column position of df1
df1. insert ( 2 , ' rebounds ', df2[' rebounds '])
#view updated DataFrame
print (df1)
team position rebounds points
0 AG 12 4
1 GA 7 4
2 AF 8 6
3 AC 8 8
4 BG 5 9
5 BC 11 5
โปรดทราบว่าคอลัมน์ ตีกลับ ของ DataFrame ที่สองได้ถูกเพิ่มไปยังตำแหน่งคอลัมน์ที่สามของ DataFrame แรกแล้ว
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีการทำงานทั่วไปอื่นๆ ในแพนด้า:
วิธีเปลี่ยนลำดับคอลัมน์ใน Pandas
วิธีเปลี่ยนชื่อคอลัมน์ใน Pandas
วิธีจัดเรียงคอลัมน์ตามชื่อใน Pandas