I'm writing a logic for KPI calculation and struggling to find a correct algorithm to get the first (min) date when event occured. We have:
Type Date Code Order
1 01/01/2020 123 A
-1 02/01/2020 123 A
1 01/02/2020 321 B
-1 03/02/2020 321 B
1 04/02/2020 321 B
1 01/06/2020 111 C
1 02/06/2020 111 C
1 02/06/2020 111 C
-1 03/06/2020 111 C
1 01/07/2020 222 D
1 01/08/2020 333 E
1 01/08/2020 333 E
-1 01/08/2020 333 E
-1 01/08/2020 333 E
1 02/08/2020 333 E
Rules: PAIRS in col 'Type' that sum into 0 for same 'Code', 'Order' are removed. What I want to do is to get either ranking or category such that:
Type Date Code Order Category
1 01/01/2020 123 A Remove
-1 02/01/2020 123 A Remove
1 01/02/2020 321 B Remove
-1 03/02/2020 321 B Remove
1 04/02/2020 321 B Keep
1 01/06/2020 111 C Keep
1 02/06/2020 111 C Keep
1 02/06/2020 111 C Remove
-1 03/06/2020 111 C Remove
1 01/07/2020 222 D Keep
1 01/08/2020 333 E Remove
1 01/08/2020 333 E Remove
-1 01/08/2020 333 E Remove
-1 01/08/2020 333 E Remove
1 02/08/2020 333 E Keep
Once this is done I can use pivot_table to get min of Date for each Code-Order. Categorization of what to remove and what to keep is a struggle.
I tried to compare with next value in row to see if that works and it does, but not for all cases. I tried
df["Match"] = df.Type.eq(df.Type.shift(periods=-1))
but it does not work for cases when I have only one row for each Order and Code, especially if it is the last one in the row.