本文介绍了查找最接近输入值的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在努力解决这个问题.我有一个看起来像这样的熊猫数组
I am struggling with this problem. I have an pandas array which looks like this
delta_n column_1 ...
0 10 10 ...
1 20 0
2 30 0
现在我有一个数字,假设我搜索 delta_n=20.5
并且我想选择最接近 delta_n 数字的行.
Now i have a number, lets say i search for delta_n=20.5
and I want to select the row closest to the number of delta_n.
我的输出应该是:
1 20 0
我用 df.loc[20.5]
尝试过,但由于它不在 pd 数据帧中,所以它不起作用.
I tried it with df.loc[20.5]
but as it is not in the pd dataframe it doesn't work.
谢谢,R
推荐答案
通过 sub
,通过abs
,通过idxmin
和最后选择 loc
:
idx = df['delta_n'].sub(delta_n).abs().idxmin()
#added double [[]] for one row DataFrame
df1 = df.loc[[idx]]
print (df1)
delta_n column_1
1 20 0
#output Series with one []
s = df.loc[idx]
print (s)
delta_n 20
column_1 0
Name: 1, dtype: int64
详情:
print (df['delta_n'].sub(delta_n))
0 -10.5
1 -0.5
2 9.5
Name: delta_n, dtype: float64
print (df['delta_n'].sub(delta_n).abs())
0 10.5
1 0.5
2 9.5
Name: delta_n, dtype: float64
print (df['delta_n'].sub(delta_n).abs().idxmin())
1
numpy.argmin 的另一种 numpy 职位解决方案
并通过 iloc
:
pos = df['delta_n'].sub(delta_n).abs().values.argmin()
print (pos)
1
df1 = df.loc[[pos]]
print (df1)
delta_n column_1
1 20 0
s = df.loc[pos]
print (s)
delta_n 20
column_1 0
Name: 1, dtype: int64
这篇关于查找最接近输入值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!