我是Pandas和这个空间的新手,在这里我遇到了一个挑战--我有一个数据,就像下面这样,我需要在“心情”栏中搜索一个名为“过敏”的值,然后从结果数据中选择包含“过敏”的行,以及基于日期在此之前的行。因此,在这个例子中,它包括了“过敏前2天”的行。
我的数据看起来像是:-
id food date mood
id 1 nuts 2018-11-12 high
id 2 potatoes 2018-11-13 low
id 3 fish 2018-11-14 high
id 4 bread 2018-11-14 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我想要实现的是提供如下内容的代码:
id food date mood
id 2 potatoes 2018-11-13 low
id 3 fish 2018-11-14 high
id 4 bread 2018-11-14 high
id 5 fish 2018-11-14 high
id 6 nuts 2018-11-14 high
id 7 fish 2018-11-15 allergies
id 9 bread 2018-11-17 high
id 10 fish 2018-11-18 high
id 11 pasta 2018-11-19 allergies因此,当“心情=过敏”时,返回前两天的“食物”条目。
我希望最终能得出这样的结果,即普通食物项目被理解为“鱼”,并将这些信息反馈给用户,如:-
"Did you realize that when you eat fish you get allergies" 有人能告诉我使用Pandas的正确方法吗?
谢谢
云母
发布于 2019-12-18 11:17:17
创建由allergies进行比较的助手系列,通过Series.cumsum更改顺序并使用累积和,然后传递给GroupBy.cumcount,第二列和第三列由isin进行比较
s = df['mood'].eq('allergies').iloc[::-1].cumsum()
df = df[df.groupby(s).cumcount(ascending=False).isin([1,2])]
print (df)
id food date mood
1 id 2 potatoes 2018-11-13 low
2 id 3 fish 2018-11-14 high
4 id 5 bread 2018-11-16 high
5 id 6 fish 2018-11-17 high细节
print (s)
6 1
5 1
4 1
3 2
2 2
1 2
0 2
Name: mood, dtype: int32另一种解决办法是:
s = df['mood'].eq('allergies').iloc[::-1].cumsum().sort_index()
df = df[(df.groupby(s).cumcount(ascending=False) < 3) & s.duplicated(keep='last')]
print (df)
id food date mood
1 id 2 potatoes 2018-11-13 low
2 id 3 fish 2018-11-14 high
4 id 5 bread 2018-11-16 high
5 id 6 fish 2018-11-17 highhttps://stackoverflow.com/questions/59390818
复制相似问题