Python: 带有 if 语句的 numpy where 命令

Python: numpy where command with if statement

我有一个数据框 df,其中包含一列字符串格式的日期,如 '2011-12-13' 和一列时间,同样采用字符串格式,如 '15:40:00'

df

index                 date        time
2011-01-03 09:40:00   2011-01-03  09:40:00 
2011-01-03 09:45:00   2011-01-03  09:45:00 
2011-01-03 09:50:00   2011-01-03  09:50:00  
2011-01-03 09:55:00   2011-01-03  09:55:00 
2011-01-03 10:00:00   2011-01-03  10:00:00  
2011-01-03 10:05:00   2011-01-03  10:05:00  

我的 objective 是在我的数据框中创建一个列 F0,其中 F0=1 如果日期属于这些日期中的任何一个 ('2011-01-26','2011-03-15', '2011-08-09', '2011-09-21', '2011-12-13') 并且 time ='9:40:00'.

我正在尝试使用 numpy 函数 where,如下所示:

dates = ['2011-01-26','2011-03-15', '2011-08-09', '2011-09-21', '2011-12-13']

df['F1'] = np.where((df.date == any(dates) & (df.time== '9:40:00'), 1, 0))

我收到这个错误: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 为什么?我不知道如何正确使用any函数。

我想为其他 time 间隔创建 F2F3 等多个列,例如:

df['F77'] = np.where((df.date == any(dates) & (df.time== '16:00:00'), 1, 0))

您不需要使用 where。只需使用 isin 并将您的条件直接应用于列:

df['F1'] = df.date.isin(dates) & (df.time=='09:40:00')