Home > Software design >  Get the column numerically closest to a specific column from all columns in a pandas dataframe
Get the column numerically closest to a specific column from all columns in a pandas dataframe

Time:04-04

I wonder if it is possible to get the column whose value is closest to a specific column from all data frames without iterating over all the columns. I.e. if there is some built in functionality or an efficient way to do this? I see so many elegant solutions here, I felt like there must be for this scenario too

Example:

|--A--|--B--|--C--|--closest to C--|
|  1  |  2  |  3  |       B        |
|  5  |  2  |  6  |       A        |

Thanks for any tips and insights.

CodePudding user response:

Subtract all columns without C by DataFrame.sub, get absolute values and get column by minimal values by DataFrame.idxmin:

df['new'] = df.drop('C', 1).sub(df.C, axis=0).abs().idxmin(axis=1)
print (df)
   A  B  C new
0  1  2  3   B
1  5  2  6   A
  • Related