[英]Count data in overlapping rolling windows on pandas dataframe
I need to count events on a pandas dataframe using rolling windows with overlaps.我需要使用重叠的滚动 windows 来计算 pandas dataframe 上的事件。
In particular, I have a dataframe with discontinuous events in time, like this:特别是,我有一个 dataframe 与时间不连续的事件,像这样:
Ma
2000-01-04 2.2
2000-01-05 2.6
2000-01-06 3.1
2000-01-16 2.4
2000-01-22 2.1
2000-01-27 2.5
2000-02-12 2.3
2000-02-19 3.5
2000-02-21 2.4
2000-02-27 2.4
and I want to count how many events occurred in time windows of 10 days with an overlap of 5 days.我想计算在 10 天的时间 windows 中发生了多少事件,重叠 5 天。 This is the result which i'm looking for:这是我正在寻找的结果:
Events
from 2000-01-04 to 2000-01-14 3
from 2000-01-09 to 2000-01-19 1
from 2000-01-14 to 2000-01-24 2
from 2000-01-19 to 2000-01-29 2
Have you got any suggestions?你有什么建议吗? I tried to use groupby but I can only count data in non overlapping windows, using this line: df.groupby(pd.DatetimeIndex(df.Time).to_period("10d")).size()
我尝试使用 groupby,但我只能使用以下行计算非重叠 windows 中的数据: df.groupby(pd.DatetimeIndex(df.Time).to_period("10d")).size()
I tried also Rolling.count from Pandas dataframe but again without success.我也尝试了 Pandas dataframe 中的 Rolling.count 但再次没有成功。
My approach is to create a data frame with a 5 day interval based on the minimum and maximum dates in the original data frame.我的方法是根据原始数据框中的最小和最大日期创建一个间隔为 5 天的数据框。 Based on that, I extract the number of items above row i and below row i+2 and calculate the number of items.基于此,我提取第 i 行以上和第 i+2 行以下的项目数并计算项目数。 . . and then list them in a loop process.然后在循环过程中列出它们。 Finally, we put it in a data frame.最后,我们将其放入数据框中。 I'm sure there are better approaches.我确信有更好的方法。
import pandas as pd
import numpy as np
import io
data = '''
date Ma
2000-01-04 2.2
2000-01-05 2.6
2000-01-06 3.1
2000-01-16 2.4
2000-01-22 2.1
2000-01-27 2.5
2000-02-12 2.3
2000-02-19 3.5
2000-02-21 2.4
2000-02-27 2.4
'''
df = pd.read_csv(io.StringIO(data), sep='\s+')
df['date'] = pd.to_datetime(df['date'])
df2 = pd.DataFrame({'date':pd.date_range(df['date'].min(), df['date'].max(), freq='5D')})
tmp = []
for i in range(len(df)):
try:
cnt = df[(df['date'] >= df2.date[i])&(df['date'] <= df2.date[i+2])].count()
fromto = 'from'+ str(df2.date[i].strftime('%Y-%m-%d'))+'to'+str(df2.date[i+2].strftime('%Y-%m-%d'))
tmp.append([fromto, cnt[0]])
except:
break
df3 = pd.DataFrame(tmp, columns=['FromTo', 'Events'])
df3
FromTo Events
0 from2000-01-04to2000-01-14 3
1 from2000-01-09to2000-01-19 1
2 from2000-01-14to2000-01-24 2
3 from2000-01-19to2000-01-29 2
4 from2000-01-24to2000-02-03 1
5 from2000-01-29to2000-02-08 0
6 from2000-02-03to2000-02-13 1
7 from2000-02-08to2000-02-18 1
8 from2000-02-13to2000-02-23 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.