Tokyo
Tokyo

Reputation: 823

How to get the value closest to another value in Pandas Dataframe

Assuming that I have the following dataframe:

           col1       col2
0          blue      0.400
1          test      0.255
2        yellow      0.460

How can I get the single value from col2 which is closest to the corresponding value where col1='test'? To make things more clear, I want to find the value closest to 0.255 (which in this case is 0.400) and then the corresponding value in col1 that has the closest value, i.e. in this case it would be blue.

Upvotes: 1

Views: 148

Answers (3)

piRSquared
piRSquared

Reputation: 294198

idxmin

def s(d, t): return d.sub(d.pop(t)).abs().idxmin()
df.set_index('col1').col2.pipe(s, t='test')

'blue'

Same thing but with min and dict

d = dict(zip(df.col1, df.col2))

v = d.pop('test')
min(d, key=lambda x: abs(d[x] - v))

'blue'

Upvotes: 2

ansev
ansev

Reputation: 30920

Use:

m = df['col1'].eq('test')
df.loc[df['col2'].sub(df['col2'].where(m)
                                .bfill()
                                .ffill())
                 .abs()
                 .mask(m).idxmin(),'col2']

or

m = df['col1'].eq('test')
df.loc[df['col2'].sub(df.loc[m,'col2'].iloc[0])
                 .abs()
                 .mask(m).idxmin(),'col2']

Output

0.4

References

Upvotes: 1

Binyamin Even
Binyamin Even

Reputation: 3382

df.loc[(df['col2']-df[df['col1']=='test']['col2'].values).abs().sort_values().index[1]]['col2']

output:

Out[38]: 0.4

Upvotes: 1

Related Questions