📜  Python| numpy nanmedian()函数

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

Python| numpy nanmedian()函数

numpy.nanmedian()函数可用于计算数组的中位数,忽略 NaN 值。如果数组有 NaN 值,我们可以在不受 NaN 值影响的情况下找出中位数。让我们看看关于 numpy.nanmedian() 方法的不同类型的示例。

示例 #1:

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


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


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([[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 (2, 3)
Median of array without using nanmedian function: nan
Using nanmedian function: 23.0

示例 #2:

Python3

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

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([[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]