2

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

2
  • 2
    just multiply : 0 returns 0 and 1 returns the amount value: df.drop('amount',1).mul(df['amount'],axis=0) Commented Mar 22, 2020 at 17:12
  • but I'm running into errors Please provide the entire error message, as well as a minimal reproducible example. Asn aside, why you use 0/1 instead of actual boolean values? Commented Mar 22, 2020 at 17:43

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

For a more general case, maybe use df2.mask(df2 != 0, df2['amount'], axis=0)
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.