jay queue
jay queue

Reputation: 415

pandas: replace values by row based on condition

I have a pandas dataframe as follows:

df2
   amount  1  2  3  4
0   5      1  1  1  1
1   7      0  1  1  1
2   9      0  0  0  1
3   8      0  0  1  0
4   2      0  0  0  1

What I want to do is replace the 1s on every row with the value of the amount field in that row and leave the zeros as is. The output should look like this

   amount  1  2  3  4
0   5      5  5  5  5
1   7      0  7  7  7
2   9      0  0  0  9
3   8      0  0  8  0
4   2      0  0  0  2

I've tried applying a lambda function row-wise like this, but I'm running into errors

df2.apply(lambda x: x.loc[i].replace(0, x['amount']) for i in len(x), axis=1)

Any help would be much appreciated. Thanks

Upvotes: 2

Views: 1625

Answers (2)

Jaroslav Bezděk
Jaroslav Bezděk

Reputation: 7625

You can also do it wit pandas.DataFrame.mul() method, like this:

>>> df2.iloc[:, 1:] = df2.iloc[:, 1:].mul(df2['amount'], axis=0)
>>> print(df2)
   amount  1  2  3  4
0       5  5  5  5  5
1       7  0  7  7  7
2       9  0  0  0  9
3       8  0  0  8  0
4       2  0  0  0  2

Upvotes: 2

Scott Boston
Scott Boston

Reputation: 153460

Let's use mask:

df2.mask(df2 == 1, df2['amount'], axis=0)

Output:

   amount  1  2  3  4
0       5  5  5  5  5
1       7  0  7  7  7
2       9  0  0  0  9
3       8  0  0  8  0
4       2  0  0  0  2

Upvotes: 5

Related Questions