return rows in a dataframe closest to a user-defined number

后端 未结 2 1987
一生所求
一生所求 2020-12-24 08:07

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

2条回答
  •  抹茶落季
    2020-12-24 08:32

    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!

提交回复
热议问题