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

Python中使用Pandas合并多个DataFrame且保留索引的实现方法

Merge DataFrames While Preserving All Original Indexes

Got it, let's solve this problem. You want to combine your three DataFrames into one, keeping every original index and all columns—pandas' concat function is exactly what we need here, since it aligns data by index by default and can retain all rows from all DataFrames.

Step-by-Step Solution

First, let's start with your existing DataFrame definitions, then run the merge:

import pandas as pd
import numpy as np

# Your original DataFrames
df2 = pd.DataFrame(np.random.randint(0, 50, (3,3)), columns = ["A", "B", "C"], index = ["1", "2", "3"])
df3 = pd.DataFrame(np.random.randint(0, 50, (4,2)), columns = ["D", "E"], index = ["100", "101", "102", "103"])
df4 = pd.DataFrame(np.random.randint(0, 1000, (11,5)), columns = ["F", "G", "H", "I", "J"], index = ["1", "2", "3", "4", "5", "6", "7", "100", "101", "102", "103"])

# Merge all DataFrames by index, preserving all rows and columns
df5 = pd.concat([df2, df3, df4], axis=1, join='outer', sort=False)

What This Does

  • axis=1: Tells pandas to merge horizontally (combine columns instead of rows)
  • join='outer': Ensures all original indexes are kept—any index that exists in any of the DataFrames will be in df5. Missing values from other DataFrames will be filled with NaN
  • sort=False: Keeps the index order as they appear across your original DataFrames (remove this if you want indexes sorted numerically/alphabetically)

Example Output Structure

Your final df5 will look like this (values will vary based on the random integers):

IndexABCDEFGHIJ
1234112NaNNaN567890123456789
2103429NaNNaN321654987234567
345173NaNNaN876543210876543
4NaNNaNNaNNaNNaN111222333444555
.................................
100NaNNaNNaN2235999888777666555
101NaNNaNNaN491101202303404505

This keeps every index from all three DataFrames and combines all columns exactly as you wanted.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:04:33