Skip to main content
 首页 » 编程设计

python之将 '' 替换为 Nan 或零

2025年05月04日10zhujiabin

我有一个数据列:

Power: 
0     130 
1     165 
2     150 
3     150 
4     ? 
5     198 
6     220 
7     215 
8     225 
9     ? 
10    170 

我想替换每个 '?' Nan 或零。

我试过:

data['Power'].str.replace('?', 0).astype(float) 
data['Power'].str.replace('^[^\d]*', '').astype(float) 
data['Power'].replace(r'\s+', np.nan, regex=True) 
data['Power'].convert_objects(convert_numeric=True) 
data['Power'].replace(regex=True,inplace=True,to_replace=r'\D',value=r'') 

但这些都不起作用!

有些产生错误 could not convert string to float 而有些没有产生任何错误但没有改变 '?'。

请您参考如下方法:

如果只需要将所有非数值替换为 NaN,请使用 to_numeric :

data.Power = pd.to_numeric(data.Power, errors='coerce') 
print (data) 
    Power 
0   130.0 
1   165.0 
2   150.0 
3   150.0 
4     NaN 
5   198.0 
6   220.0 
7   215.0 
8   225.0 
9     NaN 
10  170.0 

如果需要 0 然后添加 fillna强制转换为 int:

data.Power = pd.to_numeric(data.Power, errors='coerce').fillna(0).astype(int) 
print (data) 
    Power 
0     130 
1     165 
2     150 
3     150 
4       0 
5     198 
6     220 
7     215 
8     225 
9       0 
10    170