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 indf5. Missing values from other DataFrames will be filled withNaNsort=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):
| Index | A | B | C | D | E | F | G | H | I | J |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 23 | 41 | 12 | NaN | NaN | 567 | 890 | 123 | 456 | 789 |
| 2 | 10 | 34 | 29 | NaN | NaN | 321 | 654 | 987 | 234 | 567 |
| 3 | 45 | 17 | 3 | NaN | NaN | 876 | 543 | 210 | 876 | 543 |
| 4 | NaN | NaN | NaN | NaN | NaN | 111 | 222 | 333 | 444 | 555 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 100 | NaN | NaN | NaN | 22 | 35 | 999 | 888 | 777 | 666 | 555 |
| 101 | NaN | NaN | NaN | 49 | 1 | 101 | 202 | 303 | 404 | 505 |
This keeps every index from all three DataFrames and combines all columns exactly as you wanted.
内容的提问来源于stack exchange,提问作者PratikSharma
相关产品推荐
相关产品推荐

