简体   繁体   中英

How to filter like if any group in the last row is negative or positive, just show that group. Pandas

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM