Pandas DataFrame合并问题:如何基于KO-ST字段合并df1与df2
Hey there! Let's work through merging your two DataFrames (df1 and df2) using Pandas. First, let's recap their structures based on your examples to make sure we're on the same page:
Sample DataFrame Structures
import pandas as pd # df1 sample df1 = pd.DataFrame({ 'KO-ST': ['1976-_', '991-_'], '1_UID': [200106897, 200108737], '2_Vloge': [200106897.0, 200108737.0] }) # df2 sample df2 = pd.DataFrame({ 'a': [10000002, 10000003], 'b': ['851-601', '851-1'], 'SID': [288.0, 68.0], 'KO-ST': [288.0, 68.0] })
A quick note: I noticed KO-ST is stored as strings in df1 but numeric floats in df2. This will break matching—you need to standardize the data type first! For example:
# Convert df1's KO-ST to numeric (handle non-numeric values with 'coerce') df1['KO-ST'] = pd.to_numeric(df1['KO-ST'], errors='coerce') # OR convert df2's KO-ST to string df2['KO-ST'] = df2['KO-ST'].astype(str)
Core Merge Operations
Pandas' pd.merge() is the go-to tool here. We'll use the shared KO-ST column as our merge key, and adjust the how parameter to get the type of join you need:
1. Inner Join (Default)
Keep only rows where KO-ST exists in both DataFrames:
merged_inner = pd.merge(df1, df2, on='KO-ST')
2. Left Join
Keep all rows from df1, and match with df2 rows where possible (missing df2 values get filled with NaN):
merged_left = pd.merge(df1, df2, on='KO-ST', how='left')
3. Right Join
Keep all rows from df2, and match with df1 rows where possible:
merged_right = pd.merge(df1, df2, on='KO-ST', how='right')
4. Outer Join
Keep every row from both DataFrames, filling gaps with NaN where there's no match:
merged_outer = pd.merge(df1, df2, on='KO-ST', how='outer')
Extra Tips for Clean Merges
- Handle duplicate column names: If other columns share names across df1/df2, add suffixes to tell them apart:
merged_with_suffixes = pd.merge(df1, df2, on='KO-ST', suffixes=('_from_df1', '_from_df2')) - Clean messy keys: If
KO-SThas hidden whitespace, strip it first:df1['KO-ST'] = df1['KO-ST'].astype(str).str.strip() df2['KO-ST'] = df2['KO-ST'].astype(str).str.strip() - Debug missing matches: Find rows in df1 that don't have a corresponding
KO-STin df2:unmatched_df1 = df1[~df1['KO-ST'].isin(df2['KO-ST'])]
内容的提问来源于stack exchange,提问作者energyMax

