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
1200
#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.51-0.529.5
Name: delta_n, dtype: float64
print (df['delta_n'].sub(delta_n).abs())
010.510.529.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
1200
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"