Python Numpy nanmedian()
numpy.nanmedian()函数可以用来计算数组的中位数,忽略NaN值。如果数组中有NaN值,我们可以找出中位数而不受NaN值的影响。让我们看看关于numpy.nanmedian()方法的不同类型的例子。
语法:
numpy.nanmedian(a, axis=None, out=None, overwrite_input=False, keepdims=)
参数:
a: [arr_like] 输入阵列
轴:我们可以使用轴=1表示行,或轴=0表示列。
out:输出阵列
overwrite_input: 如果为真,则允许使用输入数组a的内存进行计算。输入数组将被调用median修改。
keepdims:如果设置为True,被缩小的轴会作为尺寸为1的尺寸留在结果中。有了这个选项,结果将正确地与原始的A进行对比。
返回:它在ndarray中返回中值。
示例 #1:
# Python code to demonstrate the
# use of numpy.nanmedian
import numpy as np
# create 2d array with nan value.
arr = np.array([[12, 10, 34], [45, 23, np.nan]])
print("Shape of array is", arr.shape)
print("Median of array without using nanmedian function:",
np.median(arr))
print("Using nanmedian function:", np.nanmedian(arr))
输出:
Shape of array is (2, 3)
Median of array without using nanmedian function: nan
Using nanmedian function: 23.0
示例 #2:
# Python code to demonstrate the
# use of numpy.nanmedian
# with axis
import numpy as np
# create 2d array with nan value.
arr = np.array([[12, 10, 34], [45, 23, np.nan]])
print("Shape of array is", arr.shape)
print("Median of array with axis = 0:",
np.median(arr, axis = 0))
print("Using nanmedian function:",
np.nanmedian(arr, axis = 0))
输出:
Shape of array is (2, 3)
Median of array with axis = 0: [ 28.5 16.5 nan]
Using nanmedian function: [ 28.5 16.5 34. ]
示例 #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([[12, 10, 34],
[45, 23, np.nan],
[7, 8, np.nan]])
print("Shape of array is", arr.shape)
print("Median of array with axis = 0:",
np.median(arr, axis = 1))
print("Using nanmedian function:",
np.nanmedian(arr, axis = 1))
输出:
Shape of array is (3, 3)
Median of array with axis = 0: [ 12. nan nan]
Using nanmedian function: [ 12. 34. 7.5]