I have a Multindex DataFrame with the following structure:
0 1 2 ref
A B
21 45 0.01 0.56 0.23 0.02
22 45 0.30 0.88 0.53 0.87
23 46 0.45 0.23 0.90 0.23
What I want to do with it is:
From the columns [0:2] choose the closest value to the column ‘ref’, so the expected result would be:
closest
A B
21 45 0.01
22 45 0.88
23 46 0.23
Reconstructing your
DataFrame:I would first get the absolute distance of columns
0,1and2fromref:Given now
distyou can determine the column with the min value by row usingDataFrame.idxmin:To now generate your new
closest, then you simply need to useidxto indexdf:For the last step, there might be a more elegant way to do it but I’m relatively new to Pandas and that’s the best I can think of right now.