📜  Python中的 numpy.nansum()

📅  最后修改于: 2022-05-13 01:54:23.929000             🧑  作者: Mango

Python中的 numpy.nansum()

当我们想要计算给定轴上的数组元素的总和时,使用numpy.nansum()函数,将非数字 (NaNs) 视为零。

代码#1:工作

# Python program explaining
# numpy.nansum() function
  
import numpy as geek
in_num = 10
  
print ("Input  number : ", in_num)
    
out_sum = geek.nansum(in_num) 
print ("sum of array element : ", out_sum) 

输出 :

Input  number :  10
sum of array element :  10


代码#2:

# Python program explaining
# numpy.nansum function
  
import numpy as geek
  
in_arr = geek.array([[2, 2, 2], [2, 2, geek.nan]])
   
print ("Input array : ", in_arr) 
    
out_sum = geek.nansum(in_arr) 
print ("sum of array elements: ", out_sum) 

输出 :

Input array :  [[  2.   2.   2.]
 [  2.   2.  nan]]
sum of array elements:  10.0


代码#3:

# Python program explaining
# numpy.nansum function
  
import numpy as geek
  
in_arr = geek.array([[2, 2, 2], [2, 2, geek.nan]])
   
print ("Input array : ", in_arr) 
    
out_sum = geek.nansum(in_arr, axis = 1) 
print ("sum of array elements taking axis 1: ", out_sum) 

输出 :

Input array :  [[  2.   2.   2.]
 [  2.   2.  nan]]
sum of array elements taking axis 1:  [ 6.  4.]


注意:如果同时存在正无穷大和负无穷大,则总和将不是数字 (NaN)。如果存在正无穷和负无穷之一,则总和将是存在的正无穷或负无穷。

代码#4:

# Python program explaining
# numpy.nansum() function
  
import numpy as geek
  
in_arr1 = geek.array([2, -5, geek.nan, geek.inf])
in_arr2 = geek.array([1, 4, geek.inf, -geek.inf ])
   
print ("1st array elements: ", in_arr1) 
print ("2nd array elements: ", in_arr2) 
    
out_sum1 = geek.nansum(in_arr1) 
out_sum2 = geek.nansum(in_arr2)
  
print ("sum of 1st array elements: ", out_sum1) 
print ("sum of 2nd array elements: ", out_sum2) 

输出 :

1st array elements:  [  2.  -5.  nan  inf]
2nd array elements:  [  1.   4.  inf -inf]
sum of 1st array elements:  inf
sum of 2nd array elements:  nan