Change values of a certain range of columns based on another range of columns of the same data frame

Question:

I have this df

       x      y1      y2        y3        y4             d1        d2          d3          d4
0  -17.7       7     NaN       NaN       NaN              5       NaN           4         NaN
1  -15.0     NaN     NaN       NaN         3              4       NaN         NaN           8
2  -12.5     NaN     NaN         2       NaN            NaN       NaN           1           9

I want only 1 value per row between d1 to d4, based on what value is between y1 to y4.

Example: In the 1st row, value is on y1. So the value that stays is d1.

The output would be:

       x      y1      y2        y3        y4               d1        d2          d3          d4
0  -17.7       7     NaN       NaN       NaN                5       NaN         NaN         NaN
1  -15.0     NaN     NaN       NaN         3              NaN       NaN         NaN           8
2  -12.5     NaN     NaN         2       NaN              NaN       NaN           1         NaN
Asked By: Peter M

||

Answers:

You can use where with a boolean matrix:

df[['d1', 'd2', 'd3', 'd4']] = df.filter(like='d').where(df.filter(like='y').notna().to_numpy())

Output:

      x   y1  y2   y3   y4   d1  d2   d3   d4
0 -17.7  7.0 NaN  NaN  NaN  5.0 NaN  NaN  NaN
1 -15.0  NaN NaN  NaN  3.0  NaN NaN  NaN  8.0
2 -12.5  NaN NaN  2.0  NaN  NaN NaN  1.0  NaN
Answered By: Scott Boston
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.