我正在使用Pandas中的时间序列数据(时间戳用作索引)。我正在对数据集进行一些过滤,最后得到一个数据框,其中大部分包含连续观察值(一分钟数据)。但是,也有一些时间间隔,只有一到几分钟的观察。这些我想排除。我该如何使用sth来掌握这些短间隔:
df = df.drop(df[<some boolean condition>].index)
timestamp value
2018-01-08 06:13:00 143
2018-01-08 06:14:00 324
2018-01-08 06:15:00 324
2018-01-08 06:16:00 324
2018-01-08 06:17:00 324
2018-01-08 06:20:00 324(remove)
2018-01-08 06:35:00 324
2018-01-08 06:36:00 324
2018-01-08 06:37:00 324
2018-01-08 06:38:00 324
2018-01-08 06:39:00 324
2018-01-08 06:40:00 324
答案 0 :(得分:1)
使用:
#convert index to Series
s = df.index.to_series()
#test if 1 Minute difference, then cumulative sum
a = s.diff().ne(pd.Timedelta(1, unit='Min')).cumsum()
#filter if counts of cumulative value greater like N, e.g. 3
N = 3
df = df[a.map(a.value_counts()).gt(N)]
print (df)
value
timestamp
2018-01-08 06:13:00 143
2018-01-08 06:14:00 324
2018-01-08 06:15:00 324
2018-01-08 06:16:00 324
2018-01-08 06:17:00 324
2018-01-08 06:35:00 324
2018-01-08 06:36:00 324
2018-01-08 06:37:00 324
2018-01-08 06:38:00 324
2018-01-08 06:39:00 324
2018-01-08 06:40:00 324