我有一个 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())
关于python - 删除 pandas DF 列上的空格将 bool 值转换为 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45932224/