提问人:user6118986 提问时间:7/28/2023 最后编辑:OCauser6118986 更新时间:8/1/2023 访问量:114
覆盖默认值 True == 1, False == 0 行为
Override default True == 1, False == 0 behavior
问:
我有可以包含布尔值和整数混合的数据帧,我希望能够做这样的事情,并保证如果为 1,它不会与 中的值匹配。df_1 == df_2.loc[0,0]
df_2.loc[0,0]
True
df_1
答:
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_1
True==1
False==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) 不同:BoolProofCompare
0
0.0
def BoolProofCompare(a, b):
return a == b and type(a) == type(b)
之所以不起作用,是因为在 Python 和 .return a == b
True == 1
True == 1.0
评论
0,1,'yes','no','true','false','off','on','oui','non'
df = pd.DataFrame({'col': [True, 1, False, 0]})
dtype('O')