Skip to content Skip to sidebar Skip to footer

Select Rows Per Groups And With Time Conditions

A B C 0 2002-01-16 2002-02-28 HH 1 2002-01-16 2002-01-30 DX 2 2002-01-16 2002-02-28 TY 3 2002-01-16 2002-01-30 FY 4 2002-04-28 2002-04-30 PE 5 2002-04-28

Solution 1:

Let's try:

df[df['Diff'] == df['A'].map(df[df.Diff > pd.Timedelta('2 days')]
                              .groupby('A')['Diff'].min())]

Output:

           A          B   C    Diff
1 2002-01-16 2002-01-30  DX 14 days
3 2002-01-16 2002-01-30  FY 14 days
5 2002-04-28 2002-05-25  CO 27 days
7 2002-04-28 2002-05-25  DS 27 days

Solution 2:

I will do it by two steps

s=df[((df.B-df.A).dt.days>2)]# 1st condition 
s[((s.B-s.A).dt.days.groupby(s.A).transform(lambda x : x==x.min()))]# 2nd condition 
Out[1396]: 
           A          B   C
1 2002-01-16 2002-01-30  DX
3 2002-01-16 2002-01-30  FY
5 2002-04-28 2002-05-25  CO
7 2002-04-28 2002-05-25  DS

Post a Comment for "Select Rows Per Groups And With Time Conditions"