Python Pandas - 形成两个 Index 对象的交集并对结果进行排序
pythonserver side programmingprogramming更新于 2026/1/2 14:04:17
要形成两个 Index 对象的交集,请使用 Pandas 中的 index1.intersection(index2) 方法。要对结果进行排序,请使用 sort 参数。
首先,导入所需的库 −
import pandas as pd
创建 Pandas index1 和 index2 −
index1 = pd.Index([4, 3, 2, 1]) index2 = pd.Index([8, 2, 6, 4])
显示 Pandas index1 和 index2
print("Pandas Index1...\n",index1)
print("Pandas Index2...\n",index2)
执行交集。结果使用"sort"进行排序参数
res = index1.intersection(index2, sort=None)
示例
以下是代码 −
import pandas as pd
# 创建 Pandas index1 和 index2
index1 = pd.Index([4, 3, 2, 1])
index2 = pd.Index([8, 2, 6, 4])
# 显示 Pandas index1 和 index2
print("Pandas Index1...\n",index1)
print("Pandas Index2...\n",index2)
# 返回 Index1 和 Index2 中的元素数量
print("\n索引1中的元素数量...\n",index1.size)
print("\n索引2中的元素数量...\n",index2.size)
# 执行交集
# 使用"sort" 对结果进行排序参数
res = index1.intersection(index2, sort=None)
# 两个索引的交集并返回排序结果
print("\n索引1和索引2的交集(排序结果)...\n",res)
输出
将产生以下输出 −
Pandas Index1... Int64Index([4, 3, 2, 1], dtype='int64') Pandas Index2... Int64Index([8, 2, 6, 4], dtype='int64') 索引1中的元素数量... 4 索引2中的元素数量... 4 索引1和索引2的交集(排序结果)... Int64Index([2, 4], dtype='int64')
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

