给定:
df = pd.DataFrame({'a':[0,1,2,3,0,1,2,3], 'b':[0,1,0,1,1,0,1,0]})
作为
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
创建一个掩码以识别a 或b 不为零的位置,可以安全计算。
mask = (df['a'] != 0) | (df['b'] != 0)
面具
0 False
1 True
2 True
3 True
4 True
5 True
6 True
7 True
用NaN 填充结果列,然后覆盖您可以计算的结果:
df['c'] = pd.np.NaN
df.loc[mask, 'c'] = df['a'] / (df['a'] + df['b'])
结果
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
适用于您的问题:
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'])