Pandas中Merge操作返回空DataFrame问题求助
Hey there, let's break down why your merge is returning an empty (0, 4) DataFrame and fix it right away!
The Root Cause
Your merge code has a conflicting parameter combination: you're using both right_on='Loan_ID2' and right_index=True.
When you set right_index=True, pandas ignores the right_on argument and instead tries to match data1['Loan_ID'] with the index of data2. Looking at your data, data2's index is numeric values (1, 2, 3, 4, 5) while data1['Loan_ID'] is string values like LP001003—these don't overlap at all, so no rows get matched.
The Fix
Simply remove the right_index=True parameter. You already told pandas to use data2['Loan_ID2'] to match data1['Loan_ID'] with right_on='Loan_ID2', so that's all you need.
Here's the corrected code:
data_merged = data1.merge(right=data2, how='inner', left_on='Loan_ID', right_on='Loan_ID2', sort=False)
What to Expect
After running this, data_merged.shape should return (5, 4)—all 5 rows from both datasets will be matched correctly, since every Loan_ID in data1 has a corresponding Loan_ID2 in data2.
内容的提问来源于stack exchange,提问作者user8270077

