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

如何合并存在互斥缺失行的两个表?Pandas合并方法咨询

How to Merge Two Tables with All Column Names in 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_nameValue1Value2
H156
H256
H326
H446
H656
K11365
K22531
K371
K446

Key Explanation

  • how='outer': Unlike a left join, this keeps every unique Column_name from both tables, filling in missing values with NaN (which we can replace with empty strings if needed).
  • Renaming Value columns: Prevents column name collisions and makes it obvious which values came from Table1 vs Table2.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 14:32:47