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

如何在DataFrame中对同名行的指定列值进行统一修正?

Pandas实现指定分组内的字段值替换

原始数据构建

首先还原你提供的DataFrame:

import pandas as pd

df = pd.DataFrame({
    'Name': ['YB', 'SW', 'EJ', 'EJ'],
    'Korean': [100, 90, 80, 70],
    'English': [100, 90, 80, 70],
    'Math': [100, 90, 80, 70],
    'highschool': ['A', 'B', 'C', 'D']
})

方案一:缺失值填充法

先将目标行的highschool值设为缺失值,再按Name分组向前填充同组内的有效值:

# 定位需要替换的行:Name为EJ且highschool为D
mask = (df['Name'] == 'EJ') & (df['highschool'] == 'D')
# 将目标行设为缺失值
df.loc[mask, 'highschool'] = pd.NA
# 按Name分组,向前填充同组内的有效值
df['highschool'] = df.groupby('Name')['highschool'].ffill()

方案二:同组上一行值替换法

通过shift获取同组内上一行的highschool值,直接替换目标行:

# 按Name分组,生成上一行的highschool值列
df['prev_high'] = df.groupby('Name')['highschool'].shift(1)
# 定位目标行并替换
mask = (df['Name'] == 'EJ') & (df['highschool'] == 'D')
df.loc[mask, 'highschool'] = df.loc[mask, 'prev_high']
# 删除临时生成的辅助列
df = df.drop('prev_high', axis=1)

两种方案执行后,都能得到你需要的结果:

Name  Korean  English  Math highschool
0   YB     100      100   100          A
1   SW      90       90    90          B
2   EJ      80       80    80          C
3   EJ      70       70    70          C

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 13:35:17