我正在尝试将字符串 'TRUE' 和 'FALSE' 的数据框中的列转换为布尔值。对于其他数据类型,我只是使用 astype 并且没有任何问题,但出于某种原因,在此列上使用它会将所有值转换为 True。
我对字符串列表重复了测试如下
test = ['False','False','True']
test = pd.DataFrame(test)
test = test.astype('bool')
Run Code Online (Sandbox Code Playgroud)
但它给出了相同的结果,这里发生了什么以及如何正确转换数据类型?我试过使用 map 和 replace 在转换之前更改值,但都没有改变结果。
有问题的字符串值被转换为 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
Run Code Online (Sandbox Code Playgroud)
或者:
import ast
test = test[0].map(ast.literal_eval)
print (test)
0 False
1 False
2 True
Name: 0, dtype: bool
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8960 次 |
| 最近记录: |