Skip to main content
 首页 » 编程设计

python之删除 pandas DF 列上的空格将 bool 值转换为 NaN

2025年05月04日10emanlee

我有一个 pandas 数据框,其中有一列包含字符串值和 boolean 值。由于这种差异,列的 dtype 推断为“对象”。当我在此列上运行 .str.strip() 时,它会将我所有的 boolean 值都转换为 NaN。有谁知道我该如何防止这种情况?我可以接受 boolean 值变成字符串,但是 Nan?

请您参考如下方法:

从 piRSquared 借用 df:

首先将所有值转换为string,然后剥离:

df['A'] = df['A'].astype(str).str.strip() 
print (df) 
       A 
0      a 
1      b 
2   True 
3  False 
4   True 

如果需要混合类型 - 带字符串的 boolean 值添加 combine_first将 NaN 替换为 boolean:

df['A'] = df['A'].str.strip().combine_first(df.A) 
print (df) 
       A 
0      a 
1      b 
2   True 
3  False 
4   True 

如果需要转换所有列:

df = df.astype(str).applymap(lambda x: x.strip()) 

或者:

df = df.astype(str).apply(lambda x: x.str.strip())