如果日期在日期范围内的if语句

时间:2018-12-06 21:53:25

标签: python-3.x pandas date

我正在创建一个标志,该标志在满足条件时生成1,否则为0

我正在尝试达到这种状态

enter image description here

我想创建一个代码,如果df['Won'] = 1 '2018-10-31' < df['Created Date'] < '2018-12-01'它将返回1,否则返回0

当前我的代码是:

df['Deal'] = pd.np.where((df['Won'] == 1) | (df['Created Date']>'2018-10-31'), 1, 0) 

我不确定如何修复代码

谢谢!

1 个答案:

答案 0 :(得分:2)

df['Deal'] = (df['Won'] == 1) | ( (df['Created Date']>'2018-10-31') & (df['Created Date']<'2018-12-01') )

这将返回一个布尔值,您可以使用astype(int)命令将其转换为int值。另外,我建议将这些日期字符串转换为实际的datetime对象,例如

df['Created Date'] = pd.to_datetime(df['Created Date'])

然后,您的df ['Deal']查询将更像

df['Created Date'] > dt.datetime(2018,10,31).