简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM