查找最接近输入值的行

raf*_*_sa 11 python pandas

我正在努力解决这个问题。我有一个看起来像这样的熊猫数组

               delta_n    column_1   ...
0                10      10        ...
1                20       0
2                30       0
Run Code Online (Sandbox Code Playgroud)

现在我有一个数字,假设我搜索delta_n=20.5并且我想选择最接近 delta_n 数字的行。

我的输出应该是:

1                20       0
Run Code Online (Sandbox Code Playgroud)

我试过了,df.loc[20.5]但因为它不在 pd 数据框中,所以它不起作用。

谢谢,R

jez*_*ael 11

减去值 by sub,得到绝对值 by abs,找到具有最小值的索引 byidxmin和最后选择 by 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
Run Code Online (Sandbox Code Playgroud)

详情

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
Run Code Online (Sandbox Code Playgroud)

位置 bynumpy.argmin和selection by 的另一个 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
Run Code Online (Sandbox Code Playgroud)