Python比较值触发DataFrame真值模糊ValueError如何解决?
报错原因
你直接将单个PyPDF2.generic.TextStringObject类型值和整个pandas DataFrame对象做不等比较,运算会返回一个和study1维度完全一致的布尔型DataFrame,而Python的if判断只能接收单个布尔值,无法直接处理多值的布尔结构,因此抛出了真值歧义错误。
解决方案
根据你的实际业务需求选择对应方案即可:
- 方案1:你要比较的是
study1中某一个具体单元格的值
先从study1里取出目标单个值,再统一类型后比较,示例如下:
# 示例取study1第0行第0列的值,可根据实际需求调整索引 target_val = study1.iloc[0, 0] # 统一转为字符串类型避免不同字符串类的比较异常 if str(mob.iloc[16, 1]) != str(target_val): print('Buisness Unit Value is incorrect')
- 方案2:你要判断
mob.iloc[16][1]不存在于study1的所有单元格中
通过any()方法对布尔结果做全局聚合,得到单个布尔值:
# 先统一所有值为字符串类型,再全局判断是否存在相等值 has_match = (str(mob.iloc[16, 1]) == study1.astype(str)).any(axis=None) if not has_match: print('Buisness Unit Value is incorrect')
- 方案3:你要判断
mob.iloc[16][1]和study1所有单元格的值都不相等
通过all()方法对布尔结果做全局聚合:
all_not_match = (str(mob.iloc[16, 1]) != study1.astype(str)).all(axis=None) if all_not_match: print('Buisness Unit Value is incorrect')
内容的提问来源于stack exchange,提问作者fatima
相关产品推荐
相关产品推荐

