我正在尝试将字符串“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/