如何在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
相关产品推荐
相关产品推荐

