Python:如何在我的时间序列中删除每天的前 5 分钟?

标签 python python-3.x pandas pandas-groupby timedelta

我有一个包含列的数据框:交易日期、交易时间和价格。我想在每天的前 5 分钟和最后 5 分钟内抽出时间。

这是一个例子:

----------------------------------------
Date       | Time         | Price
----------------------------------------
03/03/2014 | 09:36:36.814 |  43.90
---------------------------------------
03/03/2014 | 09:37:02.381  | 43.40
---------------------------------------
03/03/2014 | 09:41:02.381  | 43.40
---------------------------------------
03/03/2014 | 09:50:02.381  | 43.40
---------------------------------------

我想得到这个输出:

----------------------------------------
Date       | Time         | Price
---------------------------------------
03/03/2014 | 09:50:02.381  | 43.40
---------------------------------------

我需要为时间序列的每一天执行此操作。 我试过这段代码:

  trades14081.insert(2,'DateTime',pd.to_datetime(trades14081['Date']+trades14081['Time'], format = "%d/%m/%Y%H:%M:%S.%f" ))
delta=datetime.timedelta(minutes=5)
i=0
j=0
start=[]
end=[]
while trades14081['Date'][i]==trades14081['Date'][j] and j<len(trades14081):
    if trades14081['DateTime'][j]-trades14081['DateTime'][i]<delta:
        j=j+1
    else:
        start.append(i)
        end.append(j)
        j=j+1
        while trades14081['Date'][i]==trades14081['Date'][j] and j<len(trades14081):
            j=j+1
        i=j
for i in range(len(start)):
    trades14081=trades14081.drop(trades14081.index[start[i]:end[i]])

但我一直收到这个错误:

KeyError: 19996

>      12             l.append(j)
>      13             j=j+1
> ---> 14             while trades14081['Date'][i]==trades14081['Date'][j]:
>      15                 j=j+1
>      16             i=j

19996 是我的数据框 trades14081 的长度。

有什么想法吗?

最佳答案

groupby + bool 索引

您可以而且应该避免 Python 级别的循环。这里可以使用groupby:

# convert strings to timedelta
df['Time'] = pd.to_timedelta(df['Time'])

# define offset from start to omit
offset = pd.Timedelta(minutes=5)

# apply Boolean filter to dataframe
res = df.loc[df['Time'] > df.groupby('Date')['Time'].transform('min') + offset]

print(res)

          Date     Time  Price
4  03/03/2014  09:40:00     41
5  03/03/2014  09:46:00     42

关于Python:如何在我的时间序列中删除每天的前 5 分钟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53247879/

相关文章:

Python urllib3 以及如何处理 cookie 支持?

python - 上一个/下一个实例函数的 Django 查询集插值

python - 模块和变量作用域

python - TypeError : "value" parameter must be a scalar, dict 或 Series,但您在 Python 中传递了 "DataFrame"

python - 值错误 : continuous is not supported

python - groupby 和 resample 对 pandas 数据框的同时操作?

python - 有什么方法可以定义带有前导可选参数的 Python 函数?

java - Pyspark 中的广播加入得到 OnOutOfMemoryError

Python gzip 模块在 ubyte 文件上无法按预期工作

python-3.x - 用于图中第二个图的 Bokeh Hovertool