如何通过将Pandas DataFrame列与Set进行比较来创建新列表

3

我已经有一个名为"bad_outcomes"的集合和一个数据框,其中一个列名为"Outcome"。

使用"Outcome",我想创建一个列表,如果对应行的Outcome在bad_outcomes集合中,则元素为0; 否则为1。

然后我想将它分配给变量'landing_class'。

我已经写了这个:

landing_class = []

if df['Outcome'].isin(set(bad_outcomes)):
  landing_class.append(0)
else:
  landing_class.append(1)

它没有工作。我遇到了一个错误。

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
3个回答

2
首先,这个条件返回的是类似于 if {true, true, false,....} 的一系列真假值,而不能作为 if 语句的有效输入。为了解决这个问题,你需要使用 all() 或 any() 等函数之一。
但是,添加任何一个或全部只能解决错误,但并不能达到你的目标。
你有三种解决方案:
for i in df['Outcome']:
    if i in set(bad_outcomes):
        landing_class.append(0)
    else:
        landing_class.append(1) 

第二种解决方案:

landing_class = np.where(df['Outcome'].isin(set(bad_outcomes)), 0, 1)

第三种解决方案:

landing_class  = list(~df['Outcome'].isin(set(bad_outcomes))*1)

0

这段简单的代码有效:

landing_class = np.where(df['Outcome'].isin(bad_outcomes), 0, 1)

0

尝试使用这个一行代码,包括 isineqastype

landing_class = df['Outcome'].isin(bad_outcomes).eq(False).astype(int)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接