寻找Pandas中replace操作的.loc替代方案,消除SettingWithCopyWarning
Hey there, let's squash those pesky SettingWithCopyWarnings that are popping up in your production code—ignoring them isn't an option, so let's switch to explicit .loc indexing to make pandas happy.
The core issue here is that pandas suspects you're modifying a copy of a DataFrame slice instead of the original dataset. By using .loc[row_indexer, col_indexer], you're explicitly telling pandas you want to modify the original DataFrame directly.
Here are the adjusted versions of your three solutions, all using .loc to avoid warnings:
1. Map + Fillna with .loc
Instead of directly assigning to df1['Capital'], use .loc[:, 'Capital'] to target the column explicitly:
s = df2.set_index('Nation')['Capital City'] df1.loc[:, 'Capital'] = df1['Country'].map(s).fillna(df1.loc[:, 'Capital'])
This ensures pandas knows you're updating the original DataFrame's Capital column, not a slice's copy.
2. Replace with .loc
Same logic applies here—use .loc to assign the result of replace():
s = df2.set_index('Nation')['Capital City'] df1.loc[:, 'Capital'] = df1['Country'].replace(s)
3. Update with .loc
For the update() method, target the Capital column via .loc to avoid triggering the warning:
s = df2.set_index('Nation')['Capital City'] df1.loc[:, 'Capital'].update(df1['Country'].map(s))
Bonus Tip: Check if df1 is a Slice
If df1 itself was created as a slice from another larger DataFrame (e.g., df1 = main_df[main_df['Region'] == 'Europe']), pandas might still treat it as a view. To eliminate this entirely, create a copy of df1 first:
# Make a copy to ensure df1 is an independent DataFrame df1 = df1.copy() # Now run any of the above .loc-based solutions s = df2.set_index('Nation')['Capital City'] df1.loc[:, 'Capital'] = df1['Country'].map(s).fillna(df1.loc[:, 'Capital'])
内容的提问来源于stack exchange,提问作者Nabih Bawazir

