【问题标题】:If statement nested in For loop - Getting error = The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()如果语句嵌套在 For 循环中 - 获取错误 = Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()
【发布时间】:2019-12-22 08:36:05
【问题描述】:

我正在尝试为我的数据框编写一个嵌套在 for 循环中的 if 语句,如下所示:

我希望代码遍历数据帧的每一行,如果它在 Detection_Location 列中检测到“CV22”,则应将一个文件作为数据帧导入,如果在 Detection_location 列中检测到“CV23”,则应导入另一个文件与之前相同的数据帧。

我已尝试为此编写以下代码:

def Get_PHD(df2):
    if (df2['Detection_Location'] == 'CV22'):
           PHD_df = pd.read_excel(r'C:\Users\s.gaur\Desktop\LS1 - Edited file.xlsx', sheet_by_name = "Sheet1")
           return (PHD_df)
    elif (df2['Detection_Location'] == 'CV23'):
           PHD_df = pd.read_excel(r'C:\Users\s.gaur\Desktop\LS2 - Edited File.xlsx', sheet_by_name = "Sheet1")
           return (PHD_df)



for index, row in df2.iterrows():
    Get_PHD(df2)

但出现以下错误:

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

谁能帮我解决我做错的事情。

【问题讨论】:

  • 数据截图对复制没有太大帮助; Provide a copy of the DataFrame
  • @Trenton_M - 数据集实际上与图片中可见的一样小。实际上没有更多的东西。

标签: python dataframe for-loop if-statement


【解决方案1】:

这不是一个有效的布尔表达式:

if (df2['Detection_Location'] == 'CV22'):

df2['Detection_Location'] 是一列数据,而不是原子元素。因此,if 不能准确地评估为TrueFalse。因此你的错误信息。

【讨论】:

    【解决方案2】:

    在一个 for 循环中,您将 DataFrame 传递给 Get_PHD 函数,因此 df2['Detection_Location'] == 'CV22' 部分是一个带有布尔值的系列。

    只需将循环更改为:

    for index, row in df2.iterrows():
        Get_PHD(row)
    

    【讨论】:

      【解决方案3】:

      尝试将该行传递给 Get_PHD 函数并从该行调用 Detection_Location:

      def Get_PHD(row):
          if (row.Detection_Location == 'CV22'):
                 PHD_df = pd.read_excel(r'C:\Users\s.gaur\Desktop\LS1 - Edited file.xlsx', sheet_by_name = "Sheet1")
                 return (PHD_df)
          elif (row.Detection_Location == 'CV23'):
                 PHD_df = pd.read_excel(r'C:\Users\s.gaur\Desktop\LS2 - Edited File.xlsx', sheet_by_name = "Sheet1")
                 return (PHD_df)
      
      
      for index, row in df2.iterrows():
          Get_PHD(row)
      

      【讨论】:

        【解决方案4】:
        def Get_PHD(row):
            value = row.Detection_Location
            states = {'CV22': {'file': r'C:\Users\s.gaur\Desktop\LS1 - Edited file.xlsx', 'sheet': 'Sheet1'},
                      'CV23': {'file': r'C:\Users\s.gaur\Desktop\LS2 - Edited File.xlsx', 'sheet': 'Sheet1'}}
        
            try:
                return pd.read_excel(states[value]['file'], states[value]['sheet'])
            except (KeyError, FileNotFoundError) as e:
                print(e)
        
        for _, row in df2.iterrows():
            Get_PHD(row)  # the code example has df2 here, not row
        
        • try, except 包含在您处理上述更多条件的可能性中。
          • 如果你错过了Detection_Location或者文件路径不正确,代码会通知你
        • 此代码更有效,因为只需将新位置添加到states

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-10-15
          • 2021-11-20
          相关资源
          最近更新 更多