代码之家  ›  专栏  ›  技术社区  ›  SBad

多个嵌套if条件

  •  -1
  • SBad  · 技术社区  · 6 年前

    如果满足以下条件,则代码的结构是多重嵌套的:

    DF['NewColumn']=''
    
    for i in range (0, len(DF))
      if condition
        define variable etc
        if condition
          DF['NewColumn'].values[i]= some value
        else:
          DF['NewColumn'].values[i]= some value  
    

    基本上,我循环数据帧的每一行,检查条件并根据if条件集填充新列的每一行。

    抱歉,如果我的问题不够具体,但我正在寻找更有效地编码这个问题的方法。我很想听听你的想法。

    非常感谢

    1 回复  |  直到 6 年前
        1
  •  0
  •   J. Doe    6 年前

    你可以像这样矢量化你的循环

    temp = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
    condition1 = (temp["A"] > 20) & (temp["B"] < 20)
    temp["NewColumn"] = condition1.astype(int)
    condition2 = (temp["C"] > 20) & (temp["A"] < 50)
    temp["NewColumn2"] = np.where(condition2, "between", "out")