Find Row Closest Value To Input
I am struggling with this problem. I have an pandas array which looks like this delta_n column_1 ... 0 10 10 ... 1 20
Solution 1:
Subtract value by sub
, get absolute values by abs
, find index with minimal value by idxmin
and last select 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
Details:
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
Another numpy solution for positions by numpy.argmin
and selecting by 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
Post a Comment for "Find Row Closest Value To Input"