【问题标题】:How to make a new list by comparing pandas Dataframe Columns with Set如何通过将 pandas Dataframe Columns 与 Set 进行比较来制作新列表
【发布时间】:2021-10-19 01:59:30
【问题描述】:

我已经有一个名为“bad_outcomes”的集合和一个列名为“Outcome”的数据框。

使用“Outcome”,如果 Outcome 中的相应行在 set 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().

【问题讨论】:

    标签: python pandas database set conditional-statements


    【解决方案1】:

    尝试将此单线与isineqastype 一起使用:

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

    【讨论】:

      【解决方案2】:

      首先,此条件的返回是df['Outcome'].isin(set(bad_outcomes)) 是一系列真假值,如if {true, true, false,....} 并且这是对if 语句的无效输入。为了解决这个问题,你需要使用 all() 或 any() 等函数之一。

      但添加 any 或 all 只能解决错误,但并没有达到您的目标。

      你有三个解决方案:

      第一个解决方案:

      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-18
        • 2021-10-06
        • 1970-01-01
        • 2016-08-06
        • 2016-07-13
        • 1970-01-01
        • 2019-09-28
        相关资源
        最近更新 更多