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

如何在Pandas中合并两个DataFrame并重新索引以保留全部数据

解决方案:合并并重新排列DataFrame得到指定结果

原始数据定义

首先定义题目中的两个DataFrame:

import pandas as pd

df = pd.DataFrame({'Cit':[1,3,4,8,6], 'Hou':[15,10,20,45,70]}).set_index(pd.Series([0,1,2,8,4]))
df2 = pd.DataFrame({'Cit':[6,1], 'Hou':[55,29]}).set_index(pd.Series([1,3]))

方法一:按目标顺序提取行拼接

直接按照期望结果的行顺序,从两个原始DataFrame中提取对应行并拼接,最后设置新索引:

# 按目标顺序依次提取行
target_rows = [
    df.loc[0],
    df2.loc[1],
    df.loc[1],
    df.loc[2],
    df2.loc[3],
    df.loc[8],
    df.loc[4]
]

# 拼接成新DataFrame并重置临时索引
ddf = pd.DataFrame(target_rows).reset_index(drop=True)
# 设置题目要求的最终索引
ddf.index = [0,1,2,8,4,5,6]

方法二:合并后按位置选取行

先合并两个DataFrame,再通过行位置选取目标顺序的行,最后设置新索引:

# 合并两个DataFrame,保留原始索引
combined = pd.concat([df, df2])
# 按目标顺序选取对应位置的行(0:df的索引0行,5:df2的索引1行,1:df的索引1行,以此类推)
ddf = combined.iloc[[0,5,1,2,6,3,4]]
# 设置最终索引
ddf.index = [0,1,2,8,4,5,6]

验证结果

运行上述代码后,ddf的输出与题目期望完全一致:

print(ddf)
# 输出:
#    Cit  Hou
# 0    1   15
# 1    6   55
# 2    3   10
# 8    4   20
# 4    1   29
# 5    8   45
# 6    6   70

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 04:32:08