Pandas replace the value of multiple columns based on value

Viewed 17

I have a DataFrame like this one:

col1  col2 col3  col4
 0      1     0   45
 4      3   102   72
 0      0    11  101

if the value of each item in columns 1 to 3 is greater than 0, they should be replaced by the value of col4, so the expected output should be:

col1  col2  col3 col4
  0     45     0   45
 72     72    72   72
  0      0   101  101
1 Answers

You can use mask:

cols = ['col1', 'col2', 'col3']

df[cols] = df[cols].mask(df[cols]>0, df['col4'], axis=0)

Output:

   col1  col2  col3  col4
0     0    45     0    45
1    72    72    72    72
2     0     0   101   101
Related