You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas中一次性合并多个DataFrame的Index?

一行代码实现多个Pandas Index的并集

有两种简洁写法可以替代多次重复调用union的操作:

方法1:适用于Pandas 2.0及以上版本

Pandas 2.0新增了Index.union_many()方法,专门用来合并多个Index,直接传入包含所有目标Index的列表即可:

NewIdx = pd.Index.union_many([Idx1, Idx2, Idx3, Idx4, Idx5], name='depth')

也可以从第一个Index出发调用该方法:

NewIdx = Idx1.union_many([Idx2, Idx3, Idx4, Idx5]).rename('depth')

方法2:兼容Pandas 2.0以下版本

借助functools.reduce链式执行union操作,一行完成合并:

from functools import reduce
NewIdx = reduce(lambda x, y: x.union(y), [Idx1, Idx2, Idx3, Idx4, Idx5]).rename('depth')

reduce会依次将列表中的每个Index与前一次合并结果执行union,最终得到所有Index的并集,最后用rename设置名称即可。

内容的提问来源于stack exchange,提问作者roudan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 02:42:36