19

I have a user defined number which I want to compare to a certain column of a dataframe.

I would like to return the rows of a dataframe which contain (in a certain column of df, say, df.num) the 5 closest numbers to the given number x.

Any suggestions for the best way to do this without loops would be greatly appreciated.

2 Answers 2

26

I think you can use the argsort method:

>>> df = pd.DataFrame({"A": 1e4*np.arange(100), "num": np.random.random(100)})
>>> x = 0.75
>>> df.ix[(df.num-x).abs().argsort()[:5]]
         A       num
66  660000  0.748261
92  920000  0.754911
59  590000  0.764449
27  270000  0.765633
82  820000  0.732601
>>> x = 0.33
>>> df.ix[(df.num-x).abs().argsort()[:5]]
         A       num
37  370000  0.327928
76  760000  0.327921
8    80000  0.326528
17  170000  0.334702
96  960000  0.324516
4
  • 1
    Supposing we wanted to generalize this to giving us the 5 closest rows (when we have n inputs and we want to measure closeness to n distinct columns). Would you still do it this way? If n=2 (say, x=0.75,y=5.0) -- is it easiest to use "&" df.ix[(df.num1-x).abs().argsort()[:5] & (df.num2-y).abs().argsort()[:5]] ? Thank you! Jul 24, 2013 at 16:22
  • 2
    Did the pandas interface change? I need to use df.iloc instead of df.ix otherwise the fields are all NaN.
    – swenzel
    Oct 9, 2015 at 11:10
  • 1
    Ah I think the problem is with my df's index, it is not a sequence like range(len(df)). iloc however seems to work with both a "normal" index and my index. I'm not very experienced with pandas but this behavior suggests that using iloc would be more stable?
    – swenzel
    Oct 9, 2015 at 11:23
  • This is wrong. You need to do .argsort().index to handle cases where your index might not conveniently go from 0 to N-1. Jul 29, 2019 at 21:21
4

Kind of new to python and pandas but I would suggest this.

#make random df and get number
df = pd.DataFrame({'c1':0,'c2':np.random.random(100)})
x = .25
#find differences and sort
diff = df.c2.apply(lambda z: abs(x-z))
diff.sort()
#get the index for the 5 closest numbers
inds = diff.index[:5]

inds would then have the index locations from the original df for the 5 closest numbers. Hope this helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.