Multiply two columns based on a condition in a Pandas Dataframe?

Viewed 995

I am trying to multiply two columns in a pandas dataframe, but I am struggling to do so. I need to multiply column x by column y, when y is greater than 0. Otherwise, x needs to remain as it is

enter image description here

The end result should look like this table below:

enter image description here

7 Answers

Try this:

df['x'] = df['x'].where(df['y'].eq(0),df['x'].mul(df['y']))

Maybe you could use df.apply for that.

>>> df.x = df.apply(lambda var: var.x * var.y if var.y > 0 else var.x, axis=1)
>>> df
       x     y
0  150.0  0.50
1  187.5  0.75
2  460.0  1.00
3  500.0  0.00
4   30.0  0.00

Let us try

df['new'] = df.x*df.y.replace(0,1)
Out[346]: 
0    150.0
1    187.5
2    460.0
3    500.0
4     30.0
dtype: float64

How about just replacing 0 with 1s either in y or in the copy of y?

y[y == 0] = 1

return x*y

You can use apply to filter with a lambda and then multiple by your x column:

In [1]: import pandas as pd
   ...: 
   ...: df = pd.DataFrame({'x':[300,250,460,500,30],'y':[.5,.75,1,0,0]})
   ...: 
   ...: df['x'] = df['y'].apply(lambda z: z if z > 0 else 1) * df['x']
   ...: print(df)
       x     y
0  150.0  0.50
1  187.5  0.75
2  460.0  1.00
3  500.0  0.00
4   30.0  0.00

There are many ways to to do that. Here is one of them.

import pandas as pd
df = pd.DataFrame({"x": [300, 250, 460, 500, 30],
              "y": [0.5, .75, 1, 0, 0]})
df2 = df.copy()
df2["x"] = [df["x"][i]*df["y"][i] if df["y"][i]>0 else df["x"][i] for i in range(len(df))]

Try Pandas mask:

df['x'] = df['x'].mask(df.y.gt(0), df['x']*df['y'])

In [53]: df
Out[53]: 
       x     y
0  150.0  0.50
1  187.5  0.75
2  460.0  1.00
3  500.0  0.00
4   30.0  0.00
Related