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

标签 python pandas boolean whitespace strip

我有一个 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_firstNaN 替换为 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/

相关文章:

python - 像命令行模拟器一样使用 python 子进程模块

python - PyGitHub:无法访问我团队的私有(private)存储库

python - 使用 Pandas Series 修改 Pandas Multi-Index DataFrame 值

python - 连接几个 Pandas 数据框

python - django flatpages 和 i18n

python - 无法使用 BeautifulSoup 解析 twitter 隐藏输入

python - 类型错误 : unhashable type

c++ - 创建一个 boolean 函数来确定两个数组是否移位等效

mysql - SQL 搜索返回 boolean 值

PHP:函数返回值的正确 boolean 条件参数?