Find min value in column until value not changed in another value Pandas

Question:

I have a data frame:

| Col1 | Col2 | Col3 |
|------|------|------|
| 1    | A    | 6    |
| 2    | A    | 3    |
| 3    | B    | 12   |
| 4    | B    | 10   |
| 5    | A    | 12   |
| 6    | A    | -12  |
| 7    | A    | 31   |

I want to find min value until a value not changed in Col2, I used Groupby but found out its wrong,

desired df:

| Col1 | Col2 | Col3 |
|------|------|------|
| 2    | A    | 3    |
| 4    | B    | 10   |
| 6    | A    | -12  |
Asked By: CC7052

||

Answers:

Check Below code:

df['col2_shift'] = ((df.Col2 != df.Col2.shift()).cumsum())

df.assign(col3_min = df.groupby(['col2_shift','Col2'])['Col3'].transform('min')).
query('col3_min == Col3')[['Col1','Col2','col3_min']].rename(columns={'col3_min':'Col3'})

Output:

enter image description here

Answered By: Abhishek
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.