如何检查数据帧中的时间增量是否大于一分钟?



我正在尝试比较数据帧中的不同时间戳,并在时差大于一分钟时打印输出。这是我尝试运行的代码:

for e in TestDF['date']:
delta = TestDF.date.iloc[e+1] - TestDF.date.iloc[e]
if delta > datetime.timedelta(minutes=1):
print(TestDF.date.iloc[e+1])
print(TestDF.date.iloc[e])

这是我得到的错误:

值错误:无法在没有频率的情况下将整数值添加到时间戳。

但是,这似乎有效:

TimeDifference = TestDF.date.iloc[4]-TestDF.date.iloc[3]
if TimeDifference == datetime.timedelta(minutes=1):
print(TimeDifference)

输出:0 天 00:01:00

任何帮助将不胜感激。

谢谢

下面是一些示例数据:

date             open    high    low     close
0   2020-01-28 07:00:00 311.83  311.89  311.62  311.81
1   2020-01-28 07:01:00 311.80  311.98  311.80  311.85
2   2020-01-28 07:02:00 311.90  312.00  311.88  311.98
3   2020-01-28 07:03:00 312.00  312.02  311.99  311.99
4   2020-01-28 07:04:00 312.00  312.00  311.91  311.91

你只需要使用移位和布尔过滤的组合:

注意 我已更改最后一行以显示大于 1 分钟的差异。

print(df)
date    open    high     low   close
0 2020-01-28 07:00:00  311.83  311.89  311.62  311.81
1 2020-01-28 07:01:00  311.80  311.98  311.80  311.85
2 2020-01-28 07:02:00  311.90  312.00  311.88  311.98
3 2020-01-28 07:03:00  312.00  312.02  311.99  311.99
4 2020-01-28 07:06:00  312.00  312.00  311.91  311.91

首先,我们确保我们的日期是正确的日期时间

df['date'] = pd.to_datetime(df['date'])

((df['date'] - df['date'].shift()) / np.timedelta64(1,'m')) > 1)
out:
0    False
1    False
2    False
3    False
4     True
Name: date, dtype: bool

然后,您可以按数据对其进行筛选

print(df[((df['date'] - df['date'].shift()) / np.timedelta64(1,'m')) > 1])
date                 open   high     low   close
4 2020-01-28 07:06:00  312.0  312.0  311.91  311.91

最新更新