Choose two columns values based on smallest value of column

You can use the filter function to pick out the respective vx and ux columns, then get the row mininum for each :

df.assign(vx=df.filter(regex="^vx").min(1), ux=df.filter(regex="^ux").min(1))

    vx_1    ux_1    vx_2    ux_2    vx_3    ux_3    vx      ux
0   23.0    13.0    20.0    11.0    18.0    8.0     18.0    8.0
1   31.0    14.0    30.0    4.0     26.5    14.0    26.5    14.0
2   19.0    11.0    21.0    12.0    29.0    15.0    19.0    11.0
3   NaN     NaN     22.0    9.0     19.0    9.0     19.0    9.0
4   23.0    13.0    22.0    14.0    NaN      NaN    22.0    14.0
5   NaN     NaN     NaN     NaN     37.0    12.0    37.0    12.0
6   21.0    17.0    19.6    9.5     20.0    6.0     19.6    9.5

If however, you wish to get values of ‘ux’ where ‘vx’ is min, then pd.wide_to_long can be handy:

res = pd.wide_to_long(df.reset_index(), 
                     stubnames=["vx", "ux"], 
                     i="index", 
                     j="num", 
                     sep="_")

vx = res.groupby(level=0).vx.min()
ux = (res.loc[res.vx.eq(vx, axis=0), "ux"]
         .sort_index()
         .array)

df.assign(vx=vx.array, ux=ux)

    vx_1    ux_1    vx_2    ux_2    vx_3    ux_3    vx      ux
0   23.0    13.0    20.0    11.0    18.0    8.0     18.0    8.0
1   31.0    14.0    30.0    4.0     26.5    14.0    26.5    14.0
2   19.0    11.0    21.0    12.0    29.0    15.0    19.0    11.0
3   NaN     NaN     22.0    9.0     19.0    9.0     19.0    9.0
4   23.0    13.0    22.0    14.0    NaN     NaN     22.0    14.0
5   NaN     NaN      NaN    NaN     37.0    12.0    37.0    12.0
6   21.0    17.0    19.6    9.5     20.0    6.0     19.6    9.5

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top