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

如何在Python DataFrame中将0替换为字符串"NA"、其余值替换为0?

DataFrame指定值替换实现

原始数据

首先定义并创建目标DataFrame:

import numpy as np
import pandas as pd

data = {'col1': [1,2,np.nan,4],
        'col2': [1,2,0,4],
        'col3': [0,2,3,4],
        'col4': [1,2,0,np.nan],
}
df = pd.DataFrame(data)

原始输出:

col1  col2  col3  col4
0   1.0     1     0   1.0
1   2.0     2     2   2.0
2   NaN     0     3   0.0
3   4.0     4     4   NaN

需求

将DataFrame中所有0替换为字符串"NA",其余所有值(包括NaN)替换为0。

解决方案

可以使用np.where实现高效的逐元素判断替换,代码如下:

df_result = pd.DataFrame(np.where(df == 0, "NA", 0), columns=df.columns)

也可以用applymap遍历每个元素处理:

df_result = df.applymap(lambda x: "NA" if x == 0 else 0)

处理结果

执行后得到的DataFrame:

col1 col2 col3 col4
0    0    0   NA    0
1    0    0    0    0
2    0   NA    0   NA
3    0    0    0    0

说明:两种方法都会将非0的数值和NaN统一替换为0,仅保留原0值并替换为字符串"NA",完全符合需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 15:40:24