Say, I have this dataframe:
t = pd.DataFrame(data={"Pos": [1, 2, 3], "A": [10, 2, 90], "B":[90, 98, 10]})
I would like to know which of the (values in A and B >= 20) but only if (Pos = 1 or 3).
The result should look like this:
JavaScript
x
5
1
"A" "B"
2
False True
3
True True
4
True False
5
I can find the values >= 20 using t[["A", "B"]].ge(20)
but I cannot seem to find a way to add the condition based on Pos.
Would a kind soul be able to help?
Advertisement
Answer
You can use a mask:
JavaScript
1
2
1
t[['A', 'B']].ge(20).where(t['Pos'].isin([1, 3]), True)
2
Alternative with numpy.logical_or
and boolean inversion ~
:
JavaScript
1
2
1
np.logical_or(t[["A", "B"]].ge(20), ~t['Pos'].isin([1, 3]).values[:,None])
2
output:
JavaScript
1
5
1
A B
2
0 False True
3
1 True True
4
2 True False
5