Python numpy.nanmean()

Python numpy.nanmean()

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

语法:

numpy.nanmean(a, axis=None, dtype=None, out=None, keepdims=))

参数:
a: [arr_like] 输入阵列
轴:我们可以使用轴=1表示行,或轴=0表示列。
out:输出阵列
dtype:数组的数据类型
overwrite_input: 如果为真,则允许使用输入数组a的内存进行计算。输入数组将被调用median修改。
keepdims:如果设置为True,被缩小的轴会作为尺寸为1的尺寸留在结果中。有了这个选项,结果将正确地与原始的A进行对比。
返回:返回数组元素的平均值。

示例 #1:

# 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))

输出:

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

示例 #2:

# 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:

# 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.        ]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程