Computer >> Máy Tính >  >> Lập trình >> Python

Python Pandas - Hình thành Liên minh của hai đối tượng Chỉ mục với các kiểu dữ liệu khác nhau

Để tạo Liên hợp hai đối tượng Chỉ mục có kiểu dữ liệu khác nhau, hãy sử dụng index1.union (index2) trong Pandas.

Đầu tiên, hãy nhập các thư viện được yêu cầu -

import pandas as pd

Tạo chỉ mục hai gấu trúc -

index1 = pd.Index([10, 20, 30, 40, 50])
index2 = pd.Index(['p','q', 'r', 's', 't','u'])

Hiển thị chỉ mục Pandas1 và index2 -

print("Pandas Index1...\n",index1)
print("Pandas Index2...\n",index2)

Thực hiện liên hợp các kiểu dữ liệu không khớp -

res = index1.union(index2)

Ví dụ

Sau đây là mã -

import pandas as pd

# Creating two Pandas index
index1 = pd.Index([10, 20, 30, 40, 50])
index2 = pd.Index(['p','q', 'r', 's', 't','u'])

# Display the Pandas index1 and index2
print("Pandas Index1...\n",index1)
print("Pandas Index2...\n",index2)

# Return the number of elements in Index1 and Index2
print("\nNumber of elements in index1...\n",index1.size)
print("\nNumber of elements in index2...\n",index2.size)

# Perform union of mismatched datatypes
res = index1.union(index2)

# Union of both the indexes
print("\nThe index1 and index2 Union...\n",res)

Đầu ra

Điều này sẽ tạo ra kết quả sau -

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')