0

I want to filter the last row of each group. For example, you can see that ID 101 in the last row, qty is 20, ID 105 is -3, ID 106 is -12. I want to filter like if any group in the last row is negative or positive, just show that group.

Here is a sample dataframe.

import pandas as pd
d = {'id': ['101', '101', '101', '105', '105', '106', '106'], 
    'qty': [10, -2, 20, 50, -3, 50, -12],
}
df31 = pd.DataFrame(data=d)
df31

id  qty
0   101 10
1   101 -2
2   101 20
3   105 50
4   105 -3
5   106 50
6   106 -12

If the last row qty of each group is less than 0 then it will look like this

enter image description here

If the last row qty of each group is greater than 0 then it will look like this

enter image description here

How to get results like this?

BeRT2me
  • 12,699
  • 2
  • 13
  • 31
T_Ner
  • 137
  • 1
  • 8
  • Does this answer your question? [pandas: filter rows of DataFrame with operator chaining](https://stackoverflow.com/questions/11869910/pandas-filter-rows-of-dataframe-with-operator-chaining) – OrenIshShalom Jun 27 '22 at 03:51
  • @OrenIshShalom It's similar, but after trying it, it doesn't seem like it. – T_Ner Jun 27 '22 at 03:58

1 Answers1

2

Use a boolean mask:

m = df31.groupby('id')['qty'].transform('last') >= 0

Output:

# Positive
>>> df31[m]
    id  qty
0  101   10
1  101   -2
2  101   20

# Negative
>>> df31[~m]
    id  qty
3  105   50
4  105   -3
5  106   50
6  106  -12
Corralien
  • 109,409
  • 8
  • 28
  • 52