Pandas groupby: checking gaps within a group

Question:

This is my data frame, If there is a gap in Year for a particular name, Gap column should be True else False.

Name    Year       Gap
A       2008      False
A       2008      False
A       2009      True
A       2011      False
B       2010      True 
B       2013      False
Asked By: vicky

||

Answers:

You can do:

df['Gap'] = df.groupby('Name')['Year'].diff(-1).lt(-1)

Output:

0    False
1    False
2     True
3    False
4     True
5    False
Name: Year, dtype: bool
Answered By: Quang Hoang
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.