判断字符串是否在含DataFrame的列表中触发ValueError如何解决
报错原因
Python 中in运算符对列表做存在性判断时,会依次将列表内每个元素与目标值做等值比较。当元素为pandas DataFrame时,字符串"skip"与DataFrame的等值比较会返回一个逐元素判断的布尔型DataFrame,Python尝试将这个对象转为单个布尔值的时候就会触发你遇到的ValueError。
解决方案
方法1:使用带类型检查的生成器表达式配合any()判断
这是最简洁的写法,遍历的时候仅对字符串类型的元素做匹配,不会触发DataFrame的布尔值校验:
import pandas as pd df = pd.DataFrame({"df_column":["df_value"]}) a = [df, df] if any(isinstance(item, str) and item == "skip" for item in a): print("yes")
方法2:封装为通用判断函数
如果需要多次执行这类判断,可以把逻辑封装成可复用的函数:
def has_target_str(input_list: list, target: str = "skip") -> bool: for item in input_list: # 非字符串类型直接跳过比较 if isinstance(item, str) and item == target: return True return False # 调用示例 df = pd.DataFrame({"df_column":["df_value"]}) a1 = ['skip', df] a2 = [df, df] print(has_target_str(a1)) # 输出 True print(has_target_str(a2)) # 输出 False
内容的提问来源于stack exchange,提问作者Ajay Chinni
相关产品推荐
相关产品推荐

