Python熊猫用滚动窗口删除重复项
我有一个pandas数据框(大约500000行),带有日期时间索引和3列(a、b、c): 我想在10分钟的滚动窗口内搜索,并从其中一列(b列)中删除重复项,以获得如下内容:Python熊猫用滚动窗口删除重复项,python,pandas,Python,Pandas,我有一个pandas数据框(大约500000行),带有日期时间索引和3列(a、b、c): 我想在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
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\u duplicates
和rolling\u 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分钟窗口中早期元素的副本。结果可用于布尔索引
# 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]
谢谢,这是一个很好的方法。如何将其转换为多个列?因为您使用的是
df.col1.rolling
我想检查在2分钟的窗口中是否有基于两列的重复事务。还有,索引必须是基于时间的吗?你能看一看吗?连接列首先能解决你的问题吗?不!我试过了,但没有。因为两列中有一列是string,它给出了两个错误。一个无法转换为浮点。字符串类型上不允许进行第二次滚动。
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)])))
# 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]