Python Pandas - 计算两个 Index 对象的对称差异并对结果取消排序

pythonserver side programmingprogramming更新于 2026/1/2 23:40:17

要计算两个 Index 对象的对称差异并对结果取消排序,请使用 Pandas 中的 symmetric_difference() 方法。要取消排序,请使用 sort 参数并设置为 False。

首先,导入所需的库 −


import pandas as pd

创建两个 Pandas 索引 −

index1 = pd.Index([50, 30, 20, 40, 10])
index2 = pd.Index([40, 10, 60, 20, 55])

显示 Pandas index1 和 index2 −

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

执行对称差分。使用"sort"取消排序结果参数值为 False −

res = index1.symmetric_difference(index2, sort=False)

示例

以下是代码 −

import pandas as pd

# 创建两个 Pandas 索引
index1 = pd.Index([50, 30, 20, 40, 10])
index2 = pd.Index([40, 10, 60, 20, 55])

# 显示 Pandas index1 和 index2
print("Pandas Index1...\n",index1)
print("Pandas Index2...\n",index2)

# 返回元素数量在 Index1 和 Index2 中
print("\nindex1 中的元素数量...\n",index1.size)
print("\nindex2 中的元素数量...\n",index2.size)

# 执行对称差分
# 使用"sort" 对结果进行取消排序参数
res = index1.symmetric_difference(index2, sort=False)

# 两个索引的对称差值
print("\n未排序结果的 index1 和 index2 对称差值...\n",res)

输出

将产生以下输出 −

Pandas Index1...
Int64Index([50, 30, 20, 40, 10], dtype='int64')
Pandas Index2...
Int64Index([40, 10, 60, 20, 55], dtype='int64')

index1 中的元素数量...

index2 中的元素数量...
5

未排序结果的 index1 和 index2 对称差值结果...
Int64Index([50, 30, 60, 55], dtype='int64')

相关文章


有用资源