2017-08-07 44 views
1

,我有以下数据:在大熊猫的计算处理被零除

a = pd.Series([1, 2, 3]) 
b = pd.Series([0, 0, 0]) 

如果是零记名表决,我想在某些情况下

  1. 设定结果的系列产品之一
  2. 结果设置为一个特定值

但下面给“意外”的结果:

a.div(b, fill_value = 0) 
0 inf 
1 inf 
2 inf 

a.div(b).fillna(0) 
0 inf 
1 inf 
2 inf 

a.div(b).combine_first(a) 
0 inf 
1 inf 
2 inf 

我想在到达:

情况1:将数据设置为特定值

0 0 
1 0 
2 0 

情况下2:将该值设置为一个特定的系列

0 1 
1 2 
2 3 

回答

2

可以分割后使用df.replace

In [29]: (a/b).replace(np.inf, 0) 
Out[29]: 
0 0.0 
1 0.0 
2 0.0 
dtype: float64 

In [30]: (a/b).replace(np.inf, a) 
Out[30]: 
0 1.0 
1 2.0 
2 3.0 
dtype: float64 

要处理负无穷大吗?你需要:

(a/b).replace((np.inf, -np.inf), (a, a)) 
1

我想你可以ü SE Series.replace

print (a.div(b.replace(0, np.nan)).fillna(0)) 
0 0.0 
1 0.0 
2 0.0 
dtype: float64 

print (a.div(b.replace(0, np.nan)).fillna(a)) 
0 1.0 
1 2.0 
2 3.0 
dtype: float64 
1

您还可以使用np.isinf功能检查无穷大的值,然后substitue他们以0 EX-

a = np.asarray(np.arange(5)) 
b = np.asarray([1,2,0,1,0]) 

c = a/b 
c[np.isinf(c)] = 0 

#result 
>>> c 
array([ 0. , 0.5, 0. , 3. , 0. ])