Skip to main content
 首页 » 编程设计

python之Dataframe.isin() 给出此错误 : The truth value of a DataFrame is ambiguous

2025年05月04日15webabcd

你能帮忙解决这个错误吗:我在 df.isin 函数上做错了什么?

cursor = con.cursor() 
cursor.execute("""SELECT distinct date FROM raw_finmis_online_activation_temp""") 
existing_dates = [x[0] for x in cursor.fetchall()] 
 
if df[df['date'].isin(existing_dates)]: 
    print "Yes it's in there" 
else: 
    print "N" 

它给我这个错误:

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

请您参考如下方法:

df[df['date'].isin(existing_dates)] 返回数据帧。与普通序列不同,DataFrames 从 numpy.ndarray 继承了它们的真实性,这不允许您对其进行真实性检查(除非它的长度为 1 —— 这很奇怪)。

解决方案取决于您希望从该表达式中得到什么...例如如果你想检查是否至少有一个元素:

len(df[df['date'].isin(existing_dates)]) 

或者如果你想检查所有元素是否“真实”:

df[df['date'].isin(existing_dates)].all()