nan and inf in python are converted to examples of specific numeric methods

  • 2020-06-01 10:08:25
  • OfStack

preface

Recently, due to the demand of work, we have to deal with the point division of two matrices. After we get the result, we will do other calculations. We find that some built-in functions are not work. Looking at the obtained data, I found that there were many nan and inf, which caused the basic function of Python to not work, because the denominator appeared 0 in the process of dividing. In order for the results to be processed by other python functions, especially the numpy library, it is necessary to convert nan, inf into a type recognized by python.

I'm going to substitute nan, inf for 0 as an example. Here's a look at the details:

Code 1.


import numpy as np 
a = np.array([[np.nan, np.nan, 1, 2], [np.inf, np.inf, 3, 4], [1, 1, 1, 1], [2, 2, 2, 2]]) 
print a 
where_are_nan = np.isnan(a) 
where_are_inf = np.isinf(a) 
a[where_are_nan] = 0 
a[where_are_inf] = 0 
print a 
print np.mean(a) 

2. Operation results


[[ nan nan 1. 2.] 
 [ inf inf 3. 4.] 
 [ 1. 1. 1. 1.] 
 [ 2. 2. 2. 2.]] 
[[ 0. 0. 1. 2.] 
 [ 0. 0. 3. 4.] 
 [ 1. 1. 1. 1.] 
 [ 2. 2. 2. 2.]] 
1.375 

conclusion


Related articles: