เพื่อผนวก (append) ชุด Index หลายชุดเข้าด้วยกัน ให้ใช้เมธอด append() ใน Pandas
เริ่มต้นด้วยการนำเข้าไลบรารีที่จำเป็น:
import pandas as pd
สร้าง Pandas Index:
index1 = pd.Index([10, 20, 30, 40, 50])
แสดง Pandas Index:
print("Pandas Index...\n", index1)
สร้าง Index ใหม่ที่จะผนวก:
index2 = pd.Index([60, 70, 80])
ผนวก Index ใหม่:
print("\nAfter appending...\n", index1.append(index2))
ตัวอย่างโค้ดเต็ม
import pandas as pd
# Creating Pandas index
index1 = pd.Index([10, 20, 30, 40, 50])
# Display the Pandas index
print("Pandas Index...\n", index1)
# Return the number of elements in the Index
print("\nNumber of elements in the index...\n", index1.size)
# create a new index to be appended
index2 = pd.Index([60, 70, 80])
# Append the new index
print("\nAfter appending...\n", index1.append(index2))
เอาต์พุต
จะได้ผลลัพธ์ดังนี้:
Pandas Index... Int64Index([10, 20, 30, 40, 50], dtype='int64') Number of elements in the index... 5 After appending... Int64Index([10, 20, 30, 40, 50, 60, 70, 80], dtype='int64')