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

Pandas中使用.loc修改指定行时误改全列值的问题求助

How to Only Update Specific Values in the 'Country Name' Column (Avoid Overwriting Entire Rows)

I totally get the frustration here—your original code was trying to rename specific country entries in the Country Name column, but instead it overwrote every column in those rows with the country name string. Let's fix that.

Why Your Original Code Caused the Issue

When you use:

GDP.loc[GDP['Country Name'] == 'Korea, Rep.'] = 'South Korea'

You're telling Pandas to select all rows where the country name matches, then set all columns in those rows to the string 'South Korea'. That's why your entire row got replaced instead of just the target column.

The Corrected Code

To target only the Country Name column for updates, you need to explicitly specify it in the .loc indexer. Here's the fixed version:

import pandas as pd  # Ensure this is imported if you haven't already

# Read the data as before
GDP = pd.read_excel("GDP_in.xls", skiprows=4)

# Update ONLY the 'Country Name' column for each target country
GDP.loc[GDP['Country Name'] == 'Korea, Rep.', 'Country Name'] = 'South Korea'
GDP.loc[GDP['Country Name'] == 'Iran, Islamic Rep.', 'Country Name'] = 'Iran'
GDP.loc[GDP['Country Name'] == 'Hong Kong SAR, China', 'Country Name'] = 'Hong Kong'

# Proceed with setting index and slicing columns
GDP = GDP.set_index(['Country Name'])
GDP = GDP.iloc[:, 49:59]

Breakdown of the Fix

  • The .loc syntax here follows the pattern: df.loc[row_condition, target_column] = new_value
  • This ensures that only the specified column (Country Name) gets updated for the rows that match your condition, leaving all other columns in those rows intact.

Bonus: A More Efficient Alternative (Optional)

If you have multiple renames to do, you can use replace() on the Country Name column to make the code cleaner:

country_mapping = {
    'Korea, Rep.': 'South Korea',
    'Iran, Islamic Rep.': 'Iran',
    'Hong Kong SAR, China': 'Hong Kong'
}

GDP['Country Name'] = GDP['Country Name'].replace(country_mapping)

This achieves the same result but is easier to maintain if you add more country renames later.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 11:05:49