python - 为什么 .astype ('bool' ) 将所有值转换为 True?

标签 python pandas

我正在尝试将字符串“TRUE”和“FALSE”的数据框中的列转换为 bool 值。对于其他数据类型,我只是使用 astype 并且没有任何问题,但由于某种原因在此列上使用它会将所有值转换为 True。

我对字符串列表重复了测试,如下

test = ['False','False','True']
test = pd.DataFrame(test)
test = test.astype('bool')

但它给出了相同的结果,这里发生了什么以及如何正确转换数据类型?我尝试使用映射和替换来更改转换前的值,但都没有改变结果。

最佳答案

有问题strings values are converted to Trues .

解决方案:

test = ['False','False','True']
test = pd.DataFrame(test)
test = test[0].map({'False':False, 'True':True})
print (test)
0    False
1    False
2     True
Name: 0, dtype: bool

或者:

import ast

test = test[0].map(ast.literal_eval)
print (test)
0    False
1    False
2     True
Name: 0, dtype: bool

关于python - 为什么 .astype ('bool' ) 将所有值转换为 True?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52089711/

相关文章:

python - 将 Pandas 中的 CSV 文件导入 Pandas 数据框

python - platform.system 和 platform.linux_distribution 究竟输出什么?

python - 在 python 中使用正则表达式拆分带括号的字符串

python - 从 DataFrame 到嵌套字典

python - 将 numpy 数组作为行添加到 pandas 中,并以字符串作为索引

python - 更快地读取 CSV 文件

python - 值错误 : zero-size array to reduction operation maximum

python - Pandas:如何制作双列数据框?

python - 为什么在我遍历 pandas DataFrame 后这个函数 "take"不起作用?

python - 当另一列增加/减少时添加状态列