Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีผนวก (Append) สอง DataFrame ใน Pandas


เพื่อผนวกแถวของ DataFrame หนึ่งกับแถวของอีก DataFrame เราสามารถใช้ฟังก์ชัน append() ของ Pandas ด้วย append() เราสามารถผนวกคอลัมน์ได้ด้วย มาลองตัวอย่างดูวิธีใช้เมธอดนี้

ขั้นตอน

  • สร้างข้อมูลตารางสองมิติ df1
  • พิมพ์ DataFrame อินพุต df1
  • สร้าง DataFrame อีกตัว df2 พร้อมชื่อคอลัมน์เดียวกัน และพิมพ์มัน
  • ใช้เมธอด append df1.append(df2, ignore_index=True) เพื่อผนวกแถวของ df2 กับ df1
  • พิมพ์ DataFrame ผลลัพธ์

ตัวอย่าง

import pandas as pd
df1 = pd.DataFrame({"x": [5, 2], "y": [4, 7], "z": [9, 3]})
df2 = pd.DataFrame({"x": [1, 3], "y": [1, 9], "z": [29, 30]})
print("Input DataFrame 1 is:\n", df1)
print("Input DataFrame 2 is:\n", df2)
df3 = df1.append(df2, ignore_index=True)
print("After appending, DataFrame is: \n", df3)

ผลลัพธ์

Input DataFrame 1 is:
   x  y  z
0  5  4  9
1  2  7  3
Input DataFrame 2 is:
   x  y   z
0  1  1  29
1  3  9  30
After appending, DataFrame is:
   x  y   z
0  5  4   9
1  2  7   3
2  1  1  29
3  3  9  30

ตอนนี้ มาใช้ชื่อคอลัมน์ที่ต่างกันสำหรับ DataFrame และใช้ append() โดยไม่มีพารามิเตอร์ ignore_index ค่าเริ่มต้นของ ignore_index คือ False

import pandas as pd
df1 = pd.DataFrame({"x": [5, 2], "y": [4, 7], "z": [9, 3]})
df2 = pd.DataFrame({"a": [1, 3], "b": [1, 9], "c": [29, 30]})
print("Input DataFrame 1 is:\n", df1)
print("Input DataFrame 2 is:\n", df2)
df3 = df1.append(df2)
print("After appending, DataFrame is: \n", df3)

ตอนนี้จะผลิตผลลัพธ์ดังนี้

Input DataFrame 1 is:
   x  y  z
0  5  4  9
1  2  7  3
Input DataFrame 2 is:
   a  b   c
0  1  1  29
1  3  9  30
After appending, DataFrame is:
     x    y    z    a    b    c
0  5.0  4.0  9.0  NaN  NaN  NaN
1  2.0  7.0  3.0  NaN  NaN  NaN
0  NaN  NaN  NaN  1.0  1.0  29.0
1  NaN  NaN  NaN  3.0  9.0  30.0