Given:
df = pd.DataFrame({'a':[0,1,2,3,0,1,2,3], 'b':[0,1,0,1,1,0,1,0]})
as
a b
0 0 0
1 1 1
2 2 0
3 3 1
4 0 1
5 1 0
6 2 1
7 3 0
Create a mask to identify where a
or b
is not zero which are safe to calculate on.
mask = (df['a'] != 0) | (df['b'] != 0)
the mask
0 False
1 True
2 True
3 True
4 True
5 True
6 True
7 True
Fill the result column with NaN
then overwrite the ones you can calculate:
df['c'] = pd.np.NaN
df.loc[mask, 'c'] = df['a'] / (df['a'] + df['b'])
result
a b c
0 0 0 NaN
1 1 1 0.500000
2 2 0 1.000000
3 3 1 0.750000
4 0 1 0.000000
5 1 0 1.000000
6 2 1 0.666667
7 3 0 1.000000
Applied to your question:
mask = (df['fruits_ratio'] != 0) | (df['vegetables_ratio'] != 0)
df['new_col'] = pd.np.NaN
df.loc[mask, 'new_col'] = df['fruits_ratio'] / (df['fruits_ratio'] + df['vegetables_ratio'])