简体   繁体   English

熊猫:根据条件按行替换值

[英]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.

相关问题 根据 Pandas 中的条件将多行的值替换为另一行的值 - Replace the values of multiple rows with the values of another row based on a condition in Pandas 根据条件将 Pandas DataFrame 中的一行替换为“NaN” - Replace a row in Pandas DataFrame with 'NaN' based on condition pandas groupby 并根据条件替换行值 - pandas groupby and replace rows values based on a condition 根据条件更改 pandas df 一行中的值 - Change values in a row of pandas df based on a condition 使用 pandas 根据条件分组中的上个月最后一个值,将所有空值替换为最后一行 - Using pandas replace all empty values with last row based on previous month last value in a group by condition Pandas:根据条件用另一个数据帧值替换数据帧中的值 - Pandas: replace values in dataframe with another dataframes values based on condition Pandas - 将基于索引条件的值替换为不同的值 - Pandas - Replace values based on index condition to different values 根据条件,用相应的列名替换 pandas 数据框中的特定值, - Replace specific values in pandas dataframe with the corresponding column name, based on a condition, Pandas:如何根据 ID 和条件替换面板数据集中的列值 - Pandas: How to replace column values in panel dataset based on ID and condition 将python pandas df替换为基于条件的第二个数据帧的值 - Replace python pandas df with values of a second dataframe based with condition
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM