Skip to main content
 首页 » 编程设计

python之在其他列上标记条件

2024年10月17日9freeliver54

我想执行以下操作(在伪代码中):

for each row of my dataframe; 
    if the value of the cell "date" is between the values of the cells "begin" and "end", then write "1" in the cell "flag", 0 otherwise 

我尝试了以下方法:

df['flag'] = 1 
df['flag'] = df['flag'].apply(lambda x:x if (df['begin'] < df['date'] and df['date'] < df['end']) else 0) 
# (I'm coming from R...) 

然后我得到:

The truth value of a Series is ambiguous 

我明白 Python 告诉我的意思,在这种情况下,它不是比较每行单元格的内容,而是比较整列。

我怎样才能得到我想要的? (该解决方案不必遵循相同的方法,我是 Python 新手,在这里学习)

谢谢。

请您参考如下方法:

你想要

df['flag'] = ((df['date'] > df['begin']) & (df['date'] < df['end'])).astype(int) 

假设日期是日期时间并且您的开始和结束是日期字符串这应该可以工作

这个问题:

df['flag'] = df['flag'].apply(lambda x:x if (df['begin'] < df['date'] and df['date'] < df['end']) else 0) 

首先if不明白如何处理 bool 数组因此出现错误,另外要比较多个条件,您应该使用按位运算符 & , |和 ~对于 and , or , 和 not分别。此外,由于运算符的优先级,必须将多个条件括在括号中 ()

所以 ((df['date'] > df['begin']) & (df['date'] < df['end']))将返回一个 bool 系列,然后您可以使用 astype(int) 转换类型转换 True至 1和 False至 0