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

如何优雅合并多个DataFrame的索引并定义新增索引的函数?

优雅实现索引合并方案

一、批量合并c1-c10的索引到b

你原来的链式union写法过于繁琐,这里提供两种更简洁的实现方式:

方法1:兼容所有Pandas版本(借助functools.reduce)

先将所有目标DataFrame存入列表,再通过reduce批量合并索引:

import functools
import pandas as pd

# 将c1到c10放入列表统一管理
dfs = [c1, c2, c3, c4, c5, c6, c7, c8, c9, c10]
# 批量合并所有DataFrame的索引
combined_index = functools.reduce(lambda idx_a, idx_b: idx_a.union(idx_b), [df.index for df in dfs])
# 赋值给b的索引
b.index = combined_index

方法2:Pandas 2.0+专属(用Index.union_many)

Pandas 2.0及以上版本新增了union_many方法,直接传入索引列表即可完成批量合并,代码更简洁直观:

import pandas as pd

dfs = [c1, c2, c3, c4, c5, c6, c7, c8, c9, c10]
combined_index = pd.Index.union_many([df.index for df in dfs])
b.index = combined_index

二、添加新DataFrame索引到b的函数

定义一个简单函数,接收新的DataFrame,将其索引与b的现有索引取并集后重新赋值:

def add_df_index_to_b(new_df):
    # 合并b的现有索引与新DataFrame的索引
    b.index = b.index.union(new_df.index)

使用时直接调用即可:

add_df_index_to_b(c11)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:45:41