首页 > 解决方案 > 在 If-Elif-Else 语句中未正确运行的赋值语句

问题描述

我正在尝试根据“合同”和“任期”列值中的值创建一个新列(称为“合同结束”)。

如果 Contract 的值为“两年”并且tenure%24 为 0、1 或 23(即 23、24、25、47、48、49、59、60 或 61),我想设置该值对于 ContractEnding 为 1。

如果我在 if 语句中添加 print 语句,它将打印,但值永远不会改变。它们是 if 语句中唯一的语句,因此它们都应该运行。

谁能帮我弄清楚我做错了什么?

df['tenure'].astype(int)
df['ContractEnding'] = 0
for idx,val in enumerate(df['Contract']):
    if df.iloc[idx]['Contract'] == 'Two year' and df.iloc[idx]['tenure']%24 in [23,0,1]:
        df.iloc[idx]['ContractEnding'] = 1
        ## Print statement here prints fine
    elif df.iloc[idx]['Contract'] == 'One year' and df.iloc[idx]['tenure']%12 in [11,0,1]:
        df.iloc[idx]['ContractEnding'] = 1
    else:
        df.iloc[idx]['ContractEnding'] = 0

标签: pythonconditional-statements

解决方案


推荐阅读