Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the pandas record with positive value closest to zero?

Tags:

python

pandas

I need to find the pandas record where the value is closest to zero AND positive.

Here is a small sample of the data:

                 Date  Budget
0 2018-02-24 11:20:16    6.35
1 2018-02-24 11:34:10    5.85
2 2018-02-24 16:41:12    3.85
3 2018-02-25 00:55:18    1.10
4 2018-02-25 01:36:47   -0.90
5 2018-02-25 03:12:51   -1.90
6 2018-02-25 11:29:31   -2.90
7 2018-02-25 18:20:35   -3.65

The closest I got was using a SO answer:

near_zero = df['Budget'].abs().min()

That returns only the value and not the record plus the value is a converted negative value. (index[4]) I need a search pattern that will for this sample, return both column values index[3], the lowest positive value of 'Budget'

like image 854
Timothy Lombard Avatar asked Sep 07 '25 11:09

Timothy Lombard


2 Answers

Use boolean indexing for filter positive values and then get min:

near_zero = df.loc[df['Budget'] > 0, 'Budget'].min()
print (near_zero)
1.1

and then if possible multiple mins:

df1 = df[df['Budget'] == near_zero]
print (df1)

                 Date  Budget
3 2018-02-25 00:55:18     1.1

Or if only one minimal value, thanks @coldspeed:

df1 = df.loc[[df.loc[df['Budget'] > 0, 'Budget'].idxmin()]]
print (df1)

                 Date  Budget
3 2018-02-25 00:55:18     1.1
like image 79
jezrael Avatar answered Sep 09 '25 00:09

jezrael


Or try using clip:

near_zero=df['Budget'].clip(lower=0).replace(0,np.inf).min()

Or clip_lower:

near_zero=df['Budget'].clip_lower(0).replace(0,np.inf).min()

And both cases:

print(near_zero)

Is:

1.1
like image 37
U12-Forward Avatar answered Sep 09 '25 02:09

U12-Forward