如何使用Python检查时间窗口中是否存在某些值
我有数据帧如何使用Python检查时间窗口中是否存在某些值,python,datetime,pandas,dataframe,group-by,Python,Datetime,Pandas,Dataframe,Group By,我有数据帧df。我想检查一下,在最近的记录中,是否有任何项目在过去6天内没有代码B df= item Date code X 3/5/2016 A X 3/6/2016 B X 3/10/2016 A X 3/12/2016 B Y 3/5/2016 B Y 3/7/2016 A Y 3/9/2016 A Y 3/10/2016 A Z 3/4/2016 B Z 3/9/2016 A Z
df
。我想检查一下,在最近的记录中,是否有任何项目在过去6天内没有代码B
df=
item Date code
X 3/5/2016 A
X 3/6/2016 B
X 3/10/2016 A
X 3/12/2016 B
Y 3/5/2016 B
Y 3/7/2016 A
Y 3/9/2016 A
Y 3/10/2016 A
Z 3/4/2016 B
Z 3/9/2016 A
Z 3/10/2016 A
Z 3/13/2016 A
result = [Y,Z]
以下是我的尝试:我创建了一个列来表示检查日期。我按项目分组,过滤掉旧记录,并说如果没有代码为B的记录,请保留它。但我的代码似乎没有这么做!感谢您的帮助
df['Date2'] = pd.to_datetime(df['Date'])
grouped = df.groupby('item')
df['check date'] = (grouped['Date2'].transform(lambda grp: grp.max()-pd.Timedelta(days=6)))
df2 = df.loc[(df['date2'] > df['check date'])]
result=pd.Series(df2['code']<>'B')
df['Date2']=pd.to_datetime(df['Date'])
分组=df.groupby('项目')
df['check date']=(分组为['Date2'].transform(lambda grp:grp.max()-pd.Timedelta(days=6)))
df2=df.loc[(df['date2']>df['check date'])]
结果=pd.系列(df2['code']'B')
IIUC您需要使用和(&
)添加条件(df['code']!='B')
,然后:
或者,如果您需要检查groupby的所有值是否不是B
使用:
谢谢你的接受。你也可以投票。谢谢
df['Date2'] = pd.to_datetime(df['Date'])
grouped = df.groupby('item')
df['check date'] = (grouped['Date2'].transform(lambda grp: grp.max()-pd.Timedelta(days=6)))
df2 = df.loc[(df['Date2'] > df['check date']) & (df['code'] != 'B')]
print df2
item Date code Date2 check date
2 X 3/10/2016 A 2016-03-10 2016-03-06
5 Y 3/7/2016 A 2016-03-07 2016-03-04
6 Y 3/9/2016 A 2016-03-09 2016-03-04
7 Y 3/10/2016 A 2016-03-10 2016-03-04
9 Z 3/9/2016 A 2016-03-09 2016-03-07
10 Z 3/10/2016 A 2016-03-10 2016-03-07
11 Z 3/13/2016 A 2016-03-13 2016-03-07
print df2.item.unique()
['X' 'Y' 'Z']
df2 = df.loc[(df['Date2'] > df['check date'])]
print df2
item Date code Date2 check date
2 X 3/10/2016 A 2016-03-10 2016-03-06
3 X 3/12/2016 B 2016-03-12 2016-03-06
4 Y 3/5/2016 B 2016-03-05 2016-03-04
5 Y 3/7/2016 A 2016-03-07 2016-03-04
6 Y 3/9/2016 A 2016-03-09 2016-03-04
7 Y 3/10/2016 A 2016-03-10 2016-03-04
9 Z 3/9/2016 A 2016-03-09 2016-03-07
10 Z 3/10/2016 A 2016-03-10 2016-03-07
11 Z 3/13/2016 A 2016-03-13 2016-03-07
print df2.groupby('item').filter(lambda x: (x.code != 'B').all())
item Date code Date2 check date
9 Z 3/9/2016 A 2016-03-09 2016-03-07
10 Z 3/10/2016 A 2016-03-10 2016-03-07
11 Z 3/13/2016 A 2016-03-13 2016-03-07
print df2.groupby('item').filter(lambda x: (x.code != 'B').all()).item.unique()
['Z']