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

如何基于MultiIndex替换pandas.DataFrame中的值?

基于MultiIndex用df2替换df1对应行数据

需求说明

  • 现有两个列结构完全相同的pandas.DataFrame:df1和df2
  • df2的所有MultiIndex均存在于df1中,但df1包含部分df2没有的索引
  • 二者共有的索引行,用df2的对应行数据替换df1内容;仅df1拥有的索引行,保留df1原数据
    简言之:基于MultiIndex用df2的值替换df1的对应值

示例代码与预期输出

示例数据定义

import pandas as pd

index_names = ['index1', 'index2']
columns = ['column1', 'column2']

# 定义df1
data1 = [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6]] 
index1 = [['i1', 'i1', 'i1', 'i2', 'i2'], ['A', 'B', 'C', 'B', 'C']]
df1 = pd.DataFrame(data1, index=pd.MultiIndex.from_arrays(index1, names=index_names), columns=columns)
print("df1原始数据:")
print(df1)
# 输出:
#               column1  column2
#index1 index2                  
#i1     A             1        2
#       B             2        3
#       C             3        4
#i2     B             4        5
#       C             5        6

# 定义df2
data2 = [[11, 12], [12, 13]]
index2 = [['i2', 'i1'], ['C', 'C']]
df2 = pd.DataFrame(data2, index=pd.MultiIndex.from_arrays(index2, names=index_names), columns=columns)
print("\ndf2原始数据:")
print(df2)
# 输出:
#               column1  column2
#index1 index2                  
#i2     C            11       12
#i1     C            12       13

预期输出

column1  column2
index1 index2                  
i1     A             1        2
       B             2        3
       C            12       13 # 已替换
i2     B             4        5
       C            11       12 # 已替换

环境信息

  • Python 3.10.5
  • Pandas 1.4.3

解决方案

方法1:直接修改df1(原地替换)

利用DataFrame.loc定位重叠索引,直接赋值替换,操作简单高效:

# 用df2的值替换df1中对应索引的行
df1.loc[df2.index] = df2
print(df1)

该方法会直接修改原始的df1,执行后df1即为预期结果。

方法2:生成新的DataFrame(不修改原数据)

如果需要保留原始df1和df2,可使用combine_first方法,再重新对齐索引:

# 用df2覆盖重叠行,df1补充缺失行
result = df2.combine_first(df1)
# 按照原df1的索引顺序重新排列
result = result.reindex(df1.index)
print(result)

此方法会生成一个新的DataFrame,原始的df1和df2不会被修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 20:51:33