Let's say that I have a DataFrame like this one
import pandas as pd
df = pd.DataFrame([
[1, 2, 1], [1, 3, 2], [4, 6, 3], [4, 3, 4], [5, 4, 5]
], columns=['A', 'B', 'C'])
>> df
A B C
0 1 2 1
1 1 3 2
2 4 6 3
3 4 3 4
4 5 4 5
The original DataFrame is more complicated with more columns and rows.
I want to get the first row that fulfills some criteria. Examples:
- Get first row where A > 3 (returns row 2)
- Get first row where A > 4 AND B > 3 (returns row 4)
- Get first row where A > 3 AND (B > 3 OR C > 2) (returns row 2)
But, if there isn't any row that fulfills the specific criteria, then I want to get the first one after I just sort it descending by A (or other cases by B, C etc).
- Get first row where A > 6 (returns row 4 by ordering it by A desc and get the first one)
I was able to do it by iterating on the DataFrame (I know that craps :P). So, what would be a more pythonic way to solve it?