Python: How to replace only 0 values in a column by multiplication of 2 columns in Dataframe with a loop?

Viewed 307

Here is my Dataframe:

df={'pack':[2,2,2,2], 'a_cost':[10.5,0,11,0], 'b_cost':[0,6,0,6.5]}

It should look like this:

this

At this point you will find that a_cost and b_cost columns have 0s where other column has a value. I would like my function to follow this logic...

for i in df.a_cost:
    if i==0:
       b_cost(column):value *(multiply) pack(column):value
       replace 0 with this new multiplied value (example: 6.0*2=12)
for i in df_b.cost:
    if i==0:
       a_cost(column):value /(divide) pack(column):value
       replace 0 with this new divided value (example: 10.5/2=5.25)

I can't figure out how to write this logic successfully... Here is the expected output:

Dataframe

Output in code:

df={'pack':[2,2,2,2], 'a_cost':[10.5,12.0,11,13.0], 'b_cost':[5.25,6,5.50,6.5]}

Help is really appreciated!

3 Answers

IIUC,

df.loc[df.a_cost.eq(0), 'a_cost'] = df.b_cost * df.pack
df.loc[df.b_cost.eq(0), 'b_cost'] = df.a_cost / df.pack

You can also play with mask and fillna:

df['a_cost'] = df.a_cost.mask(df.a_cost.eq(0)).fillna(df.b_cost * df.pack)
df['b_cost'] = df.b_cost.mask(df.b_cost.eq(0)).fillna(df.a_cost / df.pack)

Update as commented, you can use other in mask:

df['a_cost'] = df.a_cost.mask(df.a_cost.eq(0), other=df.b_cost * df.pack)

Also note that the second filtering is not needed once you already fill 0 in columns a_cost. That is, we can just do:

df['b_cost'] = df.a_cost / df.pack

after the first command in both methods.

Output:

   pack  a_cost  b_cost
0     2    10.5    5.25
1     2    12.0    6.00
2     2    11.0    5.50
3     2    13.0    6.50

Try this:

df['a_pack'] = df.apply(lambda x: x['b_cost']*x['pack'] if x['a_cost'] == 0 and x['b_cost'] != 0 else x['a_cost'], axis = 1)

df['b_pack'] = df.apply(lambda x: x['a_cost']/x['pack'] if x['b_cost'] == 0 and x['a_cost'] != 0 else x['b_cost'], axis = 1)
import numpy as np
df = pd.DataFrame({'pack':[2,2,2,2], 'a_cost':[10.5,0,11,0], 'b_cost':[0,6,0,6.5]})

df['a_cost'] = np.where(df['a_cost']==0, df['pack']*df['b_cost'], df['a_cost'])
df['b_cost'] = np.where(df['b_cost']==0, df['a_cost']/df['pack'], df['b_cost'])

print (df)
#pack  a_cost  b_cost
#0     2    10.5     5.25
#1     2    12.0     6.0
#2     2    11.0     5.50
#3     2    13.0     6.5
Related