繁体   English   中英

带有滚动窗口的Python Pandas drop_duplicates

[英]Python pandas drop_duplicates with rolling window

我有一个带有日期时间索引和3列(a,b,c)的熊猫数据框(约500,000行):

                           a       b        c
2016-03-30 09:59:36.619    0       55       0
2016-03-30 09:59:41.979    0       20       0
2016-03-30 09:59:41.986    0       1        0
2016-03-30 09:59:45.853    0       1        3
2016-03-30 09:59:51.265    0       20       9
2016-03-30 10:00:03.273    0       55       26
2016-03-30 10:00:05.658    0       55       28
2016-03-30 10:00:17.416    0       156      0
2016-03-30 10:00:17.928    0       122      1073
2016-03-30 10:00:21.933    0       122      0
2016-03-30 10:00:31.937    0       122      10
2016-03-30 10:00:40.941    0       122      0
2016-03-30 10:00:51.147    10      2        0
2016-03-30 10:01:27.060    0       156      0

我想在10分钟的滚动窗口中进行搜索,并从其中一列(b列)中删除重复项,以获得如下信息:

                           a       b        c
2016-03-30 09:59:36.619    0       55       0
2016-03-30 09:59:41.979    0       20       0
2016-03-30 09:59:41.986    0       1        0
2016-03-30 09:59:51.265    0       20       9
2016-03-30 10:00:03.273    0       55       26
2016-03-30 10:00:17.416    0       156      0
2016-03-30 10:00:17.928    0       122      1073
2016-03-30 10:00:51.147    10      2        0
2016-03-30 10:01:27.060    0       156      0

drop_duplicates了将drop_duplicatesrolling_apply一起使用,但是这两个函数不能很好地配合使用,即:

pd.rolling_apply(df, '10T', lambda x:x.drop_duplicates(subset='b'))

引发错误,因为该函数必须返回一个值,而不是df。 所以这就是我到目前为止:

import datetime as dt
windows = []
for ind in range(len(df)):
    t0 = df.index[ind]
    t1 = df.index[ind]+dt.timedelta(minutes=10)

    windows.append(df[numpy.logical_and(t0<df.index,\
    df.index<=t1)].drop_duplicates(subset='b'))

在这里,我最后列出了一个10分钟的数据帧,其中删除了重复项,但是随着窗口滚动到下一个10分钟的段,有很多重叠的值。 为了保持唯一的值,我尝试了类似的方法:

new_df = []
for ind in range(len(windows)-1):
    new_df.append(pd.unique(pd.concat([pd.Series(windows[ind].index),\
    pd.Series(windows[ind+1].index)])))

但这是行不通的,并且已经开始变得混乱。 有谁有聪明的主意如何尽可能有效地解决这个问题?

提前致谢。

我希望这是有用的。 我滚动了一个函数,该函数检查最后一个值是否在10分钟的窗口内是先前元素的重复项。 结果可以与布尔索引一起使用。

# Simple example
dates = pd.date_range('2017-01-01', periods = 5, freq = '4min')
col1 = [1, 2, 1, 3, 2]
df = pd.DataFrame({'col1':col1}, index = dates)

# Make function that checks if last element is a duplicate
def last_is_duplicate(a):
    if len(a) > 1:
        return a[-1] in a[:len(a)-1]
    else: 
        return False    

# Roll over 10 minute window to find duplicates of recent elements
dup = df.col1.rolling('10T').apply(last_is_duplicate).astype('bool')

# Keep only those rows for which col1 is not a recent duplicate
df[~dup]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM