Skip to main content
 首页 » 编程设计

python之在 Pandas 中同时替换空白和空字段

2025年05月04日14虾米哥

我有一个数据框“列”,它同时有空白和 NaN(空值)。现在我想用字符串“无数据”替换空白和 NaN 字段。请就此给予一些指导。我正在使用 Python Pandas。

我的数据框列 -

Col1 
---- 
 
NaN 
New York 
NaN 

这是我试过的-

df['Col1'] = df['Col1'].replace(r'\s+', "No Data", regex=True) 
df['Col1'] = df['Col1'].replace(np.NaN, "No Data", regex=True) 

我的结果列看起来像 -

Col1 
---- 
No Data 
No data 
NewNo DataYork 
No Data 

谢谢。

请您参考如下方法:

过滤 df 以将空/空白条目设置为 NaN 然后填充这些:

In [27]:     
​ 
df = pd.DataFrame({'Col1':['',np.NaN,'New York',np.NaN]}) 
df 
Out[27]: 
       Col1 
0           
1       NaN 
2  New York 
3       NaN 
In [28]: 
 
df.loc[df['Col1'].str.len() == 0, 'Col1'] = np.NaN 
df['Col1'] = df['Col1'].fillna('No Data') 
df 
Out[28]: 
       Col1 
0   No Data 
1   No Data 
2  New York 
3   No Data