Python / Pandas被零除

laik7k3q  于 12个月前  发布在  Python
关注(0)|答案(1)|浏览(71)

我试图划分,但得到一个“ZeroDivisionError:division by zero”,尽管我在计算之前检查了0值:

df['var'] = None
df.loc[(df['use'] == 1) & (df['cont_var'] != 0) , 'var'] = (df['par1'] + df['par2'] + df['par3'] + df['par4']) / df['cont_var']

字符串
如果我检查该条件的所有唯一值,则没有任何错误:

df[(df['use'] == 1) & (df['cont_var'] != 0)]['cont_var'].unique()


我得到:array([4,2,1],dtype=object)
Python 3.9.12在笔记本中使用

2vuwiymt

2vuwiymt1#

您可以过滤列cont_var用于除法,也可以使用sum用于简化解决方案:

data = {
    'use': [1,1,1,1,1,0,0,0],
    'cont_var': [1,0,0,1,1,1,1,1],
    'par1':range(8),
    'par2':range(1,9),
    'par3':range(5,13),
    'par4':range(6,14),
}
df = pd.DataFrame(data)

mask = (df['use'] == 1) & (df['cont_var'] != 0)
df['var'] = df[['par1','par2','par3','par4']].sum(axis=1) / df.loc[mask, 'cont_var']

print(df)
   use  cont_var  par1  par2  par3  par4   var
0    1         1     0     1     5     6  12.0
1    1         0     1     2     6     7   NaN
2    1         0     2     3     7     8   NaN
3    1         1     3     4     8     9  24.0
4    1         1     4     5     9    10  28.0
5    0         1     5     6    10    11   NaN
6    0         1     6     7    11    12   NaN
7    0         1     7     8    12    13   NaN

字符串

相关问题