📜  Python| numpy.nanmean()函数

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

Python| numpy.nanmean()函数

numpy.nanmean()函数可用于计算忽略 NaN 值的数组的平均值。如果数组有 NaN 值,我们可以在不受 NaN 值影响的情况下找出平均值。

示例 #1:

Python3
# Python code to demonstrate the
# use of numpy.nanmean
import numpy as np
   
# create 2d array with nan value.
arr = np.array([[20, 15, 37], [47, 13, np.nan]])
   
print("Shape of array is", arr.shape)
   
print("Mean of array without using nanmean function:",
                                           np.mean(arr))
   
print("Using nanmean function:", np.nanmean(arr))


Python3
# Python code to demonstrate the
# use of numpy.nanmean
# with axis = 0
import numpy as np
   
# create 2d matrix with nan value
arr = np.array([[32, 20, 24],
                [47, 63, np.nan],  
                [17, 28, np.nan],
                [10, 8, 9]])
   
print("Shape of array is", arr.shape)
   
print("Mean of array with axis = 0:",
             np.mean(arr, axis = 0))
   
print("Using nanmedian function:",
      np.nanmean(arr, axis = 0))


Python3
# Python code to demonstrate the
# use of numpy.nanmedian
# with axis = 1
import numpy as np
   
# create 2d matrix with nan value
arr = np.array([[32, 20, 24],
                [47, 63, np.nan],  
                [17, 28, np.nan],
                [10, 8, 9]])
   
print("Shape of array is", arr.shape)
   
print("Mean of array with axis = 1:",
             np.mean(arr, axis = 1))
   
print("Using nanmedian function:",
      np.nanmean(arr, axis = 1))


输出:
Shape of array is (2, 3)
Mean of array without using nanmean function: nan
Using nanmean function: 26.4

示例 #2:

Python3

# Python code to demonstrate the
# use of numpy.nanmean
# with axis = 0
import numpy as np
   
# create 2d matrix with nan value
arr = np.array([[32, 20, 24],
                [47, 63, np.nan],  
                [17, 28, np.nan],
                [10, 8, 9]])
   
print("Shape of array is", arr.shape)
   
print("Mean of array with axis = 0:",
             np.mean(arr, axis = 0))
   
print("Using nanmedian function:",
      np.nanmean(arr, axis = 0))
输出:
Shape of array is (4, 3)
Mean of array with axis = 0: [ 26.5   29.75    nan]
Using nanmedian function: [ 26.5   29.75  16.5 ]

示例#3:

Python3

# Python code to demonstrate the
# use of numpy.nanmedian
# with axis = 1
import numpy as np
   
# create 2d matrix with nan value
arr = np.array([[32, 20, 24],
                [47, 63, np.nan],  
                [17, 28, np.nan],
                [10, 8, 9]])
   
print("Shape of array is", arr.shape)
   
print("Mean of array with axis = 1:",
             np.mean(arr, axis = 1))
   
print("Using nanmedian function:",
      np.nanmean(arr, axis = 1))
输出:
Shape of array is (4, 3)
Mean of array with axis = 1: [ 25.33333333          nan          nan   9.        ]
Using nanmedian function: [ 25.33333333  55.          22.5          9.        ]