Pandas 以一列中的值为目标,然后使用相应的日期戳搜索其他列

Pandas 以一列中的值为目标,然后使用相应的日期戳搜索其他列,pandas,pandas-groupby,Pandas,Pandas Groupby,我有一项任务要解决,因为我试图学习熊猫,之前曾发布过一个问题,但现在需要调整此任务,以便根据日期搜索值,而不是根据@jazrael善意帮助我的行号进行倒数 基本上,我有一个如下所示的数据帧:- id food date mood id 1 nuts 2018-11-12 high id 2 potatoes 2018-11-13 low id 4 bread 2018-11-13 high id 5 fish 2018-11-14

我有一项任务要解决,因为我试图学习熊猫,之前曾发布过一个问题,但现在需要调整此任务,以便根据日期搜索值,而不是根据@jazrael善意帮助我的行号进行倒数

基本上,我有一个如下所示的数据帧:-

id    food     date        mood
id 1  nuts     2018-11-12  high
id 2  potatoes 2018-11-13  low
id 4  bread    2018-11-13  high
id 5  fish     2018-11-14  high
id 6  nuts     2018-11-14  high
id 7  fish     2018-11-15  allergies
id 8  beer     2018-11-16  low
id 9  bread    2018-11-17  high
id 10 fish     2018-11-18  high
id 11 pasta    2018-11-19  allergies
我希望在“mood”列中搜索“allergies”,然后使用我们找到“allergies”值的行中的“date”值倒计时2天,并在食品列中捕获所有相应的食品值(同时还包括检测到过敏的行中的食品项目)

因此,生成的数据框可能如下所示(为了更好地理解问题,我将保留“日期”和“情绪”列):-

非常感谢任何帮助


micdoher

解决方案与前一种类似,只用于
过敏的日期,减去
2
天,然后按以下方式过滤:

详细信息

print (df['date'].groupby(s).transform('last'))
0   2018-11-15
1   2018-11-15
2   2018-11-15
3   2018-11-15
4   2018-11-15
5   2018-11-15
6   2018-11-19
7   2018-11-19
8   2018-11-19
9   2018-11-19
Name: date, dtype: datetime64[ns]

非常感谢你,耶斯雷尔在这里似乎工作得很好
s = df['mood'].eq('allergies').iloc[::-1].cumsum()
df = df[df['date'].ge(df['date'].groupby(s).transform('last') - pd.Timedelta(2, unit='d'))]
print (df)
      id      food       date       mood
1   id 2  potatoes 2018-11-13        low
2   id 4     bread 2018-11-13       high
3   id 5      fish 2018-11-14       high
4   id 6      nuts 2018-11-14       high
5   id 7      fish 2018-11-15  allergies
7   id 9     bread 2018-11-17       high
8  id 10      fish 2018-11-18       high
9  id 11     pasta 2018-11-19  allergies
print (df['date'].groupby(s).transform('last'))
0   2018-11-15
1   2018-11-15
2   2018-11-15
3   2018-11-15
4   2018-11-15
5   2018-11-15
6   2018-11-19
7   2018-11-19
8   2018-11-19
9   2018-11-19
Name: date, dtype: datetime64[ns]