简体   繁体   English

有没有办法在“for”循环中嵌套“if”语句,然后在新列表中返回“True”、“False”或“Unsure”?

[英]Is there a way to nest an “if” statement in a “for” loop, to then return as “True”, “False”, or “Unsure” in a new list?

I currently have a Series column ("DateDiff") in a DataFrame, and I am trying to create a new list/series next to it that returns "True", "False", or "Unsure" based on the values in the "DateDiff" column.我目前在 DataFrame 中有一个系列列(“DateDiff”),我正在尝试在它旁边创建一个新的列表/系列,根据“日期差异”列。

I've tried to create a nested if function inside a for loop, and then append these returns into a new list named "fraud".我试图在 for 循环中创建一个嵌套的 if function,然后 append 这些返回到一个名为“欺诈”的新列表中。

minus = condensed['DEATHDATE'] - condensed['STOP']
minus = minus.tolist()
fraud = []
for value in minus:
    if value in minus > 0:
        fraud.append('True')
    elif value in minus < 0:
        fraud.append('False')
    elif value in minus == 0:
        fraud.append('Unsure')

I'm expecting it to run through each line of [minus], check to see if it is >, <, or == to 0, and then return and append "True", "False", or "Unsure" to the list [list].我希望它遍历 [minus] 的每一行,检查它是否 >、< 或 == 为 0,然后返回 append “True”、“False”或“Unsure”到列表 [列表]。

Whenever I try to run the code above, I keep getting this error message.每当我尝试运行上面的代码时,我都会不断收到此错误消息。

TypeError: '>' not supported between instances of 'list' and 'int' TypeError: 'list' 和 'int' 的实例之间不支持'>'

Since you're already looping through the list, you should be using the variable value to refer to the current item in the iteration.由于您已经在遍历列表,因此您应该使用变量value来引用迭代中的当前项。 Hence, your if statement should look like this instead:因此,您的 if 语句应如下所示:

if value > 0:

Same for the others.其他人也一样。 Basically, you need to remove the in minus on each line, otherwise its comparing the whole minus list with the number 0, which is not what you want happening.基本上,您需要删除每行上in minus ,否则它将整个minus列表与数字 0 进行比较,这不是您想要发生的。

When using a for loop, you don't need to say if value in minus > 0 .使用 for 循环时,您不需要说if value in minus > 0 Minus is a list and you cannot compare lists to integers.减号是一个列表,您不能将列表与整数进行比较。 Instead all you need is if value > 0 since it is already inside the for loop.相反,您只需要if value > 0因为它已经在 for 循环内。 Your code should look like the following:您的代码应如下所示:

minus = condensed['DEATHDATE'] - condensed['STOP']
minus = minus.tolist()
fraud = []
for value in minus:
    if value > 0:
        fraud.append('True')
    elif value < 0:
        fraud.append('False')
    elif value == 0:
        fraud.append('Unsure')

Just a simple misunderstanding in your for loop.只是你的 for 循环中的一个简单的误解。 Happy Coding!快乐编码!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM