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

如何用Pandas将DataFrame列的0值替换为另一DataFrame的对应值?

解决Pandas替换DataFrame列中0值的问题

直接赋值法(最直观)

如果两个DataFrame的行是一一对应的(索引对齐),直接用loc筛选出Score为0的行,赋值为auto_df_non的对应值:

import pandas as pd

# 核心代码
auto_df.loc[auto_df['Score'] == 0.0, 'Score'] = auto_df_non['Score']

为什么你的.update没生效?

.update的逻辑是按索引+列匹配,只更新当前DataFrame中与目标DataFrame重合位置的值,但它不会主动替换0值。如果一定要用.update,需要先把0转成缺失值(NA),再让.update填充:

# 把auto_df里的0值转为缺失值
auto_df['Score'] = auto_df['Score'].replace(0.0, pd.NA)
# 用auto_df_non的Score列更新
auto_df.update(auto_df_non[['Score']])
# 若有未被替换的缺失值,可转回0(按需选择)
auto_df['Score'] = auto_df['Score'].fillna(0.0)

关键注意事项

  • 两个DataFrame必须索引完全对齐,否则会出现替换错位。如果没有共同索引,先通过唯一标识列(比如ID)设置索引:
    # 假设存在共同的ID列
    auto_df = auto_df.set_index('ID')
    auto_df_non = auto_df_non.set_index('ID')
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 13:55:36