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
If the last row qty of each group is greater than 0 then it will look like this
How to get results like this?
CodePudding user response:
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