【问题标题】:Python: How can I drop the first 5 minutes of each day in my time serie?Python:如何在我的时间序列中减少每天的前 5 分钟?
【发布时间】:2019-04-14 07:56:31
【问题描述】:

我有一个包含以下列的数据框:交易日期、交易时间和价格。我想把每天的前 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]])

但我不断收到此错误:

密钥错误: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 的长度。

有什么想法吗?

【问题讨论】:

  • 你能分享样本输入和预期输出吗?这会让我们更清楚。
  • 这个问题域看起来更适合 Observables 之类的东西。 RxJS/Marble 图表rxmarbles.com - Egghead.io 和 Angular 大学在这方面有很好的课程,如果你从 JS 的角度来看的话。也许github.com/ReactiveX/RxPY 会起作用 - 从未使用过它..

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


【解决方案1】:

groupby + 布尔索引

您可以而且应该避免 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-21
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多