如何合并存在互斥缺失行的两个表?Pandas合并方法咨询
Got it, the issue here is that you're using a left join which only preserves rows from the left table (Table1), but you need a full outer join to keep all unique Column_name entries from both tables. Plus, you'll want to rename the Value columns first to avoid conflicts and clearly distinguish which values come from each table. Here's a step-by-step solution:
Step 1: Prepare Your DataFrames
First, let's recreate your tables (skip this if you already have them loaded):
import pandas as pd # Table 1 data table1 = pd.DataFrame({ 'Column_name': ['K1', 'K2', 'K4', 'H1', 'H3', 'H6'], 'Value': [13, 25, 46, 56, 26, 56] }) # Table 2 data table2 = pd.DataFrame({ 'Column_name': ['K1', 'K2', 'K3', 'H2', 'H4'], 'Value': [65, 31, 71, 56, 46] })
Step 2: Rename Value Columns
Rename the Value columns in each table to make their source clear:
table1 = table1.rename(columns={'Value': 'Value1'}) table2 = table2.rename(columns={'Value': 'Value2'})
Step 3: Perform Full Outer Join
Use how='outer' in pd.merge() to retain all Column_name entries from both tables:
merged_table = pd.merge(table1, table2, on='Column_name', how='outer')
Step 4: Optional - Format the Output
If you want the result sorted by Column_name (matching your desired output) and replace NaN with empty strings for cleaner display:
# Sort by Column_name and reset index merged_table = merged_table.sort_values('Column_name').reset_index(drop=True) # Replace NaN with empty strings merged_table = merged_table.fillna('')
Final Output
Running the above code will give you exactly the table you wanted:
| Column_name | Value1 | Value2 |
|---|---|---|
| H1 | 56 | |
| H2 | 56 | |
| H3 | 26 | |
| H4 | 46 | |
| H6 | 56 | |
| K1 | 13 | 65 |
| K2 | 25 | 31 |
| K3 | 71 | |
| K4 | 46 |
Key Explanation
how='outer': Unlike a left join, this keeps every uniqueColumn_namefrom both tables, filling in missing values withNaN(which we can replace with empty strings if needed).- Renaming
Valuecolumns: Prevents column name collisions and makes it obvious which values came from Table1 vs Table2.
内容的提问来源于stack exchange,提问作者Arron

