I am trying to create some new columns in a dataframe which are ratios of existing columns:
df[e] = df[a]/df[b]
df[f] = df[c]/df[d]
df[g] = df[a]/df[d]
df[h] = df[b]/df[c]
...
Since some values in the columns are zeros, the code above raises the ZeroDivisionError. I tried to fix it manually with:
try:
df[e] = df[a]/df[b]
except ZeroDivisionError:
df[e] = np.nan
try:
df[f] = df[c]/df[d]
except ZeroDivisionError:
df[f] = np.nan
try:
df[g] = df[a]/df[d]
except ZeroDivisionError:
df[g] = np.nan
...
But with this code all the rows in the new columns are then np.nan instead of only those which would raise the ZeroDivisionError.
So, how could I do this correctly? Possibly while also using a for loop over the new columns without having to do it manually for each new column like I tried in the second code block.
Thank you very much!