使用 pandas 数据框,我有一个类似这样的 while 条件:
while (i+1<len(df.index)) and (pr<pb and pr>sl) and (df['Buy/Sell'].iloc[i+1]!=2):
我想添加另一个条件,即 df['Time'] 应该早于 15:25。 我通过以下方式获得了 df['Time']:
df['Time'] = df.apply(lambda x:datetime.datetime.strptime(x['Time'],'%d-%m-%Y %H:%M:%S'), axis=1)
当我将以下条件添加到 while 循环时:
and (df['Time']<datetime.time(15,25,0)):
我收到以下错误:
TypeError: Cannot convert input to Timestamp
编辑:我正在根据 while 循环对数据框中其他列中的值进行处理。如果“时间”列中的时间达到 15:27,或者如果提到的其他条件不再成立,我需要停止。如果我不需要 15:27 条件,我的代码工作得很好。
注意:df.dtypes 返回以下内容:
时间 datetime64[ns]
编辑:做
`while (i+1<len(df.index)) and (pr<pb and pr>sl) and df['Buy/Sell'].iloc[i+1]!=2) and df['time'].dt.time<datetime.time(15,27,0))`
我现在收到这个错误:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
请您参考如下方法:
你因为这一行而得到错误:
and (df['Time']<datetime.time(15,25,0)):
首先你要比较time组件而不是带有时间对象的日期时间,其次,您无法将标量与类似对象的数组进行比较,因此您需要执行以下操作:
df.loc[i, 'time'].time() < datetime.time(15,25,0)
这会访问单个行值,然后是 time属性。
理想情况下,如果可能,您不想逐行迭代,重写您的过滤并使用 dt获取 time 的访问器整个系列的属性:
df.loc[df['Time'].dt.time < datetime.time(15,25,0)]将过滤你的整个 df
