Để thực hiện phép hợp (union) của hai đối tượng Index có kiểu dữ liệu khác nhau, sử dụng phương thức index1.union(index2) trong Pandas. Kết quả sẽ có dtype object để chứa cả hai kiểu.
Các bước thực hiện
- Import thư viện:
import pandas as pd - Tạo hai Index kiểu khác nhau:
index1 = pd.Index([10, 20, 30, 40, 50])(int),index2 = pd.Index(['p','q','r','s','t','u'])(string) - Gọi
index1.union(index2).
Ví dụ hoàn chỉnh
import pandas as pd
index1 = pd.Index([10, 20, 30, 40, 50])
index2 = pd.Index(['p','q','r','s','t','u'])
print("Pandas Index1...\n", index1)
print("Pandas Index2...\n", index2)
print("\nNumber of elements in index1...\n", index1.size)
print("\nNumber of elements in index2...\n", index2.size)
# Hợp hai Index kiểu khác nhau
res = index1.union(index2)
print("\nThe index1 and index2 Union...\n", res)
Kết quả
Pandas Index1...
Int64Index([10, 20, 30, 40, 50], dtype='int64')
Pandas Index2...
Index(['p', 'q', 'r', 's', 't', 'u'], dtype='object')
Number of elements in index1...
5
Number of elements in index2...
6
The index1 and index2 Union...
Index([10, 20, 30, 40, 50, 'p', 'q', 'r', 's', 't', 'u'], dtype='object')
Giải thích: Khi hợp hai Index khác dtype, Pandas tự động chuyển kết quả sang dtype object để chứa cả số và chuỗi. Thứ tự: trước các phần tử của index1, sau đó index2 (loại bỏ trùng lặp nếu có).