覆盖默认值 True == 1, False == 0 行为

Override default True == 1, False == 0 behavior

提问人:user6118986 提问时间:7/28/2023 最后编辑:OCauser6118986 更新时间:8/1/2023 访问量:114

问:

我有可以包含布尔值和整数混合的数据帧,我希望能够做这样的事情,并保证如果为 1,它不会与 中的值匹配。df_1 == df_2.loc[0,0]df_2.loc[0,0]Truedf_1

Python pandas 数据帧 布尔运算

评论

1赞 Brian61354270 7/28/2023
您能详细说明一下“我有可以包含布尔值和整数混合的数据帧”是什么意思吗?什么类型?对象?
1赞 Tim Roberts 7/28/2023
单个列始终是单个数据类型。不能在一列中混合使用布尔值和整数。
2赞 Tim Roberts 7/28/2023
也许你应该向我们展示你正在使用的数据的示例。
2赞 topsail 7/28/2023
请注意,有时数据清理步骤很有用 - 即将所有其他混合值转换为清理布尔值。0,1,'yes','no','true','false','off','on','oui','non'
3赞 Barmar 7/28/2023
@Brian61354270我不知道 OP 的数据,但您可以使用 .dtype 为 。df = pd.DataFrame({'col': [True, 1, False, 0]})dtype('O')

答:

1赞 OCa 7/28/2023 #1

最好对数据进行预处理,以避免不同数据类型之间的冲突。但是,假设您不能在数据帧中将整数与布尔值分开,然后使用布尔检测进行增强:==

def BoolProofCompare(a, b):
    '''Override default True == 1, False == 0 behavior'''
    return a==b and isinstance(a, bool)==isinstance(b, bool)

BoolProofCompare(1, True)  # False
BoolProofCompare(0, False)  # False
BoolProofCompare(1, 1)  # True
BoolProofCompare(False, False)  # True
# and so on and so forth

现在,我收集到您要求的是单个值的逐个单元格比较,例如,与数据帧中的每个元素进行比较,例如,禁用了 和 等式。在这种情况下,请使用 applymap 将上述比较广播到每个单元格df_2[0][0]df_1True==1False==0

# my example of input dataframe
df
    col1  col2
0   True     1
1      1     2
2  False     3
3      0     4

df.applymap(lambda x : BoolProofCompare(x, True))
    col1   col2
0   True  False
1  False  False
2  False  False
3  False  False

df.applymap(lambda x : BoolProofCompare(x, False))
    col1   col2
0  False  False
1  False  False
2   True  False
3  False  False

df.applymap(lambda x : BoolProofCompare(x, 1))
    col1   col2
0  False   True
1   True  False
2  False  False
3  False  False

df.applymap(lambda x : BoolProofCompare(x, 0))
    col1   col2
0  False  False
1  False  False
2  False  False
3   True  False

我想将增强的比较封装在一个新函数中会更方便,如下所示:

def BoolProofCompare_df(df, a):
    '''
    Compare single value *a* with dataframe *df*, cell by cell, 
    with True==1 and False==0 equalities disabled.
    '''
    return df.applymap(lambda x : BoolProofCompare(x, a))
0赞 pts 7/29/2023 #2

请参阅@OCa对函数的回答。另一种实现也使 (int) 与 (float) 不同:BoolProofCompare00.0

def BoolProofCompare(a, b):
    return a == b and type(a) == type(b)

之所以不起作用,是因为在 Python 和 .return a == bTrue == 1True == 1.0