Pandas DataFrame列字符串替换未达预期问题咨询
Hey there, let's get your country name replacements working correctly! The problem here is that you're using str.replace() with a dictionary—this method doesn't support dictionary-based bulk replacements directly. Let's fix that.
The Root Cause
df['Country'].str.replace() is designed for single string/regex pattern replacements, not mapping entire values using a dictionary. When you pass a dictionary to it, it doesn't interpret the key-value pairs as replacement rules, which is why your changes aren't showing up.
The Solution
Use the native Pandas Series replace() method instead. This method natively supports dictionary inputs for exact-value replacements. Here's your updated code:
import pandas as pd from pandas import ExcelWriter from pandas import ExcelFile pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) # Load and clean the DataFrame as before df = pd.read_excel('Energy Indicators.xls', skiprows=17, skipfooter=265-227) df.drop(df.columns[[0,1]], axis=1, inplace=True) df.columns=['Country', 'Energy Supply', 'Energy Supply per Capita', '% Renewable'] # Your replacement dictionary stays the same replace_values = { "Republic of Korea": "South Korea", "United States of America": "United States", "United Kingdom of Great Britain and Northern Ireland": "United Kingdom", "China, Hong Kong Special Administrative Region": "Hong Kong" } # Use Series.replace() instead of str.replace() df['Country'] = df['Country'].replace(replace_values) # Verify the changes print(df['Country'].head())
Why This Works
The replace() method for Pandas Series accepts a dictionary where:
- Keys are the exact values you want to replace
- Values are the new values you want to use
It will scan the Country column and replace every exact match of the keys with their corresponding values.
Bonus: If You Need Partial Matches
If you ever need to replace partial strings (not exact matches), you'd use str.replace() with a regex pattern, but for your use case of full country name replacements, the native replace() method is perfect.
内容的提问来源于stack exchange,提问作者vedant aher

