Skip to content Skip to sidebar Skip to footer

Filter A Pandas Dataframe By A Condition And A Minimum Value In A Column

I have a dataframe similar to test_a test_b metric_e 0 OK NOK 12 1 OK OK 7 2 OK NOK 2 3 OK OK 55 and I want to filt

Solution 1:

Using nsmallest:

df[df['test_a']=='OK'].nsmallest(1, 'metric_e')

Output:

  test_a test_b  metric_e
2     OK    NOK         2

Solution 2:

In my opinion your solution is nice, also is possible join both rows of code together with double [] for return one row DataFrame:

df = df.loc[[df.loc[df.test_a == 'OK', 'metric_e'].idxmin()]]print (df)
  test_a test_b  metric_e
2     OK    NOK         2

Solution 3:

With the output from your code, you can try with:

df[df.metric_e==df.loc[df.test_a.eq('OK'),'metric_e'].min()].T

            2
test_a     OK
test_b    NOK
metric_e    2

If don't want transpose:

df[df.metric_e==df.loc[df.test_a.eq('OK'),'metric_e'].min()]

  test_a test_b  metric_e
2     OK    NOK         2

Solution 4:

Slice after sort_values

df.query("test_a=='OK'").sort_values('metric_e').iloc[[0]]# or head(1)
Out[658]: 
  test_a test_b  metric_e
2     OK    NOK         2

Post a Comment for "Filter A Pandas Dataframe By A Condition And A Minimum Value In A Column"