Home > Back-end >  Pandas how to filter date time for different categories?
Pandas how to filter date time for different categories?

Time:12-06

Here is my original Table

col-1   col-2
A       Day-1
A       Day-2
A       Day-4
A       Day-5
B       Day-1
B       Day-2
B       Day-3
B       Day-6
B       Day-7

I would like to get rid of all dates after a specific date for each categories, by another pd.series.

For example, if the series is

A      Day-1
B      Day-6

The original Table would become

col-1   col-2
A       Day-1
B       Day-1
B       Day-2
B       Day-3
B       Day-6

Is that possible to do this? Any advice is appreciated!

CodePudding user response:

Use Series.map by s Series, swap order or rows with GroupBy.cummax for select rows before matched values in boolean indexing:

m = df['col-1'].map(s).eq(df['col-2']).iloc[::-1].groupby(df['col-1']).cummax().iloc[::-1]
df = df[m]

print (df)
  col-1  col-2
0     A  Day-1
4     B  Day-1
5     B  Day-2
6     B  Day-3
7     B  Day-6
  • Related