Timothy Lombard
Timothy Lombard

Reputation: 967

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

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'

Upvotes: 4

Views: 5260

Answers (4)

Amit Ghosh
Amit Ghosh

Reputation: 1606

This is another similar but interesting solution with clip function

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

It is basically replacing the values less than 0 to the maximum value in the list.

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71610

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

Upvotes: 1

jezrael
jezrael

Reputation: 863301

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

Upvotes: 3

Noah B. Johnson
Noah B. Johnson

Reputation: 312

This will give you the correct value:

near_zero = df[df['Budget'] > 0].min()

Upvotes: 0

Related Questions