What I have
JavaScript
x
16
16
1
A B C D E
2
0 foo 0 1.2 1 2
3
1 foo 1 1.3 2 4
4
2 foo 2 2.1 4 5
5
3 foo 3 3.1 3 5
6
4 nan 0 0 0 0
7
5 bar 0 4.1 4 6
8
6 bar 1 1.2 5 8
9
7 bar 2 1.4 6 9
10
8 bar 3 5.0 7 9
11
9 nan 0 0 0 0
12
10 baz 0 4.1 5 0
13
11 baz 1 1.2 5 3
14
12 baz 2 1.4 6 9
15
13 baz 3 5.0 7 9
16
What I want, select first occurrence where D >= 4 for each A(key)
So end result will look like,
JavaScript
1
5
1
A B C D E
2
0 foo 2 2.1 4 5
3
1 bar 0 4.1 4 6
4
2 baz 0 4.1 5 0
5
Advertisement
Answer
You can first slice the rows that match the condition on D, then groupby
A and get the first
element of each group:
JavaScript
1
2
1
df[df['D'].ge(4)].groupby('A', sort=False).first()
2
output:
JavaScript
1
6
1
B C D E
2
A
3
foo 2 2.1 4 5
4
bar 0 4.1 4 6
5
baz 0 4.1 5 0
6