[英]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.我想要做的是用该行中的金额字段的值替换每一行上的 1,并保持零不变。 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我试过像这样逐行应用 lambda 函数,但我遇到了错误
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
:让我们使用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:你也可以用pandas.DataFrame.mul()
方法pandas.DataFrame.mul()
,像这样:
>>> 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.