2015-02-17 106 views
3

我有一个包含日期的字符串格式像'2011-12-13'和时间一列一列,再以字符串格式,像'15:40:00'一个数据帧df的Python:numpy的地方命令if语句

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 

我的目标是在我的数据帧创建科拉姆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函数。

我想创造的F2F3多列,等其他time间隔,如:

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

回答

4

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

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

太棒了@BrenBarn!我不知道'isin' – Plug4 2015-02-17 20:54:08