Pandas create new column based on division of two other columns

Viewed 2908

Hi I have the following df in which I want the new column to be the result of B/A unless B == 0 in which case take the average of C&D and divide by A so ((C+D)/2)/A.

I know how to do df["New Column"] = df["B"]/df["A"] But I am not sure how you would do it how I want. DO I need to iterate through each row of the df and use conditional if statements?

A   B   C   D   New Column  Desired Column
5   3   2   4   0.6                 0.6
6   2   2   3   0.333         0.333333333
8   4   3   4   0.5                 0.5
9   0   3   4   0             0.388888889
14  3   3   4   0.214          0.214285714
5   0   2   4   0                   0.6
1 Answers

Here you go:

import numpy as np
df["new Column"] = np.where(df["B"] != 0, df["B"]/df["A"], (df["C"]+df["D"])/2/df["A"])
Related