代码之家  ›  专栏  ›  技术社区  ›  user32882

对于pandas中的布尔列和非布尔列,And语句会令人怀疑地产生一个结果

  •  0
  • user32882  · 技术社区  · 7 年前

    我在一个数据帧中“ANDIN”一个二进制和非二进制列。令我惊讶的是,这实际上给出了一个结果(我期待着一个错误)。看看下面的代码:

    import pandas as pd
    d = {'col1':[1,1,2,2,2], 'col2':[3,4,4,4,3]}
    test_df = pd.DataFrame(data = d)
    test_df['bool1'] = [True, False, True, True, False]
    test_df['bool2'] = [True, False, True, True, True]
    test_df['col3'] = [1,3,3,5,5]
    test_df['col3'] & test_df['bool1']
    

    我得到以下结果:

    0     True
    1    False
    2     True
    3     True
    4    False
    dtype: bool
    

    熊猫如何评价这一点? col3 不是布尔/二进制的,所以我很难确定是什么驱动了这两种组合是否为布尔/二进制的决定 True 或 False ?

    1 回复  |  直到 7 年前
        1
  •  0
  •   jezrael    7 年前

    这里是铸造的 0 到 False 还有一个整数 True s:

    d = {'col1':[1,1,2,2,2], 'col2':[3,4,4,4,3]}
    test_df = pd.DataFrame(data = d)
    test_df['bool1'] = [True, False, True, True, False]
    test_df['bool2'] = [True, False, True, True, True]
    #changed first value to 0
    test_df['col3'] = [0,3,3,5,5]
    
    print (test_df['col3'] & test_df['bool1'])
    0    False
    1    False
    2     True
    3     True
    4    False
    dtype: bool
    

    它工作起来就像是 astype :

    print (test_df['col3'].astype(bool))
    0    False
    1     True
    2     True
    3     True
    4     True
    Name: col3, dtype: bool
    

    下次阅读- Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?