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

如何基于条件替换Pandas DataFrame中的值?

解决方案:替换Pandas DataFrame中指定列的特定值为同行另一列的值

这是个非常典型的DataFrame数据清洗场景,我给你提供几种简洁高效的实现方式,都能帮你达成目标:

方法1:使用replace方法结合列映射

这是最直观的方式,直接指定要替换的字符,并映射到同行的B列值(注意要把B列转为字符串类型,和A列保持类型一致):

import pandas as pd
import numpy as np

df = pd.DataFrame({'A':['1','-','-','4','5'], 'B': [5, 6, 7, 8, 9]})
# 执行替换
df['A'] = df['A'].replace('-', df['B'].astype(str))
print(df)

方法2:使用where方法做条件保留

where方法会在条件满足时保留原列的值,不满足时替换为指定值,逻辑清晰易懂:

df['A'] = df['A'].where(df['A'] != '-', df['B'].astype(str))

方法3:使用mask方法做条件替换

和where逻辑相反,mask会在条件满足时替换值,适合直接定位需要修改的行:

df['A'] = df['A'].mask(df['A'] == '-', df['B'].astype(str))

验证结果

执行上述任意一种方法后,你都会得到目标DataFrame:

A  B
0  1  5
1  6  6
2  7  7
3  4  8
4  5  9

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 05:29:08