【问题标题】:Why is .astype('bool') converting all values to True?为什么 .astype('bool') 将所有值都转换为 True?
【发布时间】:2019-02-04 23:12:14
【问题描述】:

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

我在一个字符串列表上重复了测试,如下所示

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

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

【问题讨论】:

  • 您在列表中的值是字符串而不是布尔值。
  • 你的列表包含字符串,字符串只有在为空时才会转换为False

标签: python pandas


【解决方案1】:

这样做的一个明确方法是,

test=test[0]=='True'

O/P:

0    False
1    False
2     True
Name: 0, dtype: bool
bool

【讨论】:

    【解决方案2】:

    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
    

    【讨论】:

      猜你喜欢
      • 2017-06-02
      • 1970-01-01
      • 2019-04-08
      • 1970-01-01
      • 1970-01-01
      • 2010-11-21
      • 1970-01-01
      • 2011-12-16
      • 1970-01-01
      相关资源
      最近更新 更多