【发布时间】:2018-04-07 00:40:33
【问题描述】:
每个组'ID' 的第一行有一个end_date,我正在尝试识别组内的任何行,它们的begin_date 等于第一行的end_date。我需要为与日期匹配的行返回type。如果有多个匹配项,第一个就足够了。如果没有匹配项,则返回“不存在”。
df
ID color begin_date end_date type
1 red 2017-01-01 2017-01-07 Professional
1 green 2017-01-05 2017-01-07 Aquatic
1 blue 2017-01-07 2017-01-15 Superhero
1 red 2017-01-11 2017-01-22 Chocolate
2 red 2017-02-22 2017-02-26 Professional
2 green 2017-02-26 2017-02-28 Aquatic
2 blue 2017-02-26 2017-02-28 Superhero
2 red 2017-02-27 2017-02-28 Chocolate
3 red 2017-03-11 2017-03-22 Chocolate
if df.groupby('ID')['begin_date'].first() == df.groupby('ID')['end_date'].any():
return df.groupby('ID')['end_date'].any().to_dict()
else:
return 'non-existent'
最终结果
ID type
1 Superhero
2 Aquatic
3 non-existant
【问题讨论】:
-
您的代码与您的逻辑状态不匹配。
标签: python pandas boolean pandas-groupby