📜  Python中的 numpy.nanvar()

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

Python中的 numpy.nanvar()

numpy.nanvar(arr, axis = None)计算给定数据(数组元素)沿指定轴(如果有)的方差,同时忽略 NaN 值。

例子 :

代码#1:

# Python Program illustrating 
# numpy.nanvar() method 
import numpy as np 
      
# 1D array 
arr = [20, 2, np.nan, 1, 34] 
  
print("arr : ", arr) 
print("\nnanvar of arr : ", np.nanvar(arr)) 
  
print("var of arr : ", np.var(arr)) 
  
print("\nnanvar of arr : ", np.nanvar(arr, dtype = np.float32)) 
print("var of arr : ", np.var(arr, dtype = np.float32)) 
  

输出 :

arr :  [20, 2, nan, 1, 34]

nanvar of arr :  187.1875
var of arr :  nan

nanvar of arr :  187.1875
var of arr :  nan


代码#2:

# Python Program illustrating 
# numpy.nanvar() method 
import numpy as np 
      
  
# 2D array 
arr = [[2, 2, 2, 2, 2], 
    [15, 6, np.nan, 8, 2], 
    [23, 2, 54, 1, 2, ], 
    [np.nan, 44, 34, 7, 2]] 
  
      
# nanvar of the flattened array 
print("\nnanvar of arr, axis = None : ", np.nanvar(arr)) 
  
print("\nvar of arr, axis = None : ", np.var(arr)) 
  
      
# nanvar along the axis = 0 
print("\nnanvar of arr, axis = 0 : \n", np.nanvar(arr, axis = 0)) 
  
print("\nvar of arr, axis = 0 : ", np.var(arr, axis = 0)) 
  
# nanvar along the axis = 1 
print("\nnanvar of arr, axis = 1 : ", np.nanvar(arr, axis = 1)) 

输出 :

nanvar of arr, axis = None :  249.88888888888889

var of arr, axis = None :  nan

nanvar of arr, axis = 0 : 
 [ 74.88888889 312.75       458.66666667   9.25         0.        ]

var of arr, axis = 0 :  [   nan 312.75    nan   9.25   0.  ]

nanvar of arr, axis = 1 :  [  0.      22.1875 421.84   313.1875]