python中位数为nan_Python Scipy stats.nanmedian()用法及代码示例

本文介绍了如何使用Python Scipy库的nanmedian()函数计算包含Nan值的数组的中位数。通过示例代码展示了在不同维度数据上的应用,以及与普通median()函数的区别。
摘要由CSDN通过智能技术生成

scipy.stats.nanmedian(array, axis=0)函数通过忽略沿数组指定轴的数组元素的Nan(不是数字)值来计算中位数。

参数:

array:具有元素(包括Nan值)的输入数组或对象,以计算中位数。

axis:计算中值所沿的轴。默认情况下轴= 0

返回:基于设置参数的数组元素的中位数(忽略Nan值)。

代码1:

# median

import scipy

import numpy as np

arr1 = [1, 3, np.nan, 27, 2, 5]

print("median using nanmedian:", scipy.nanmedian(arr1))

print("median without handling nan value:", scipy.median(arr1))

输出:

median using nanmedian:3.0

median without handling nan value:nan

代码2:多维数据

# median

from scipy import median

from scipy import nanmedian

import numpy as np

arr1 = [[1, 3, 27],

[3, np.nan, 6],

[np.nan, 6, 3],

[3, 6, np.nan]]

print("median is:", median(arr1))

print("median handling nan:", nanmedian(arr1))

# using axis = 0

print("\nmedian is with default axis = 0:\n",

median(arr1, axis = 0))

print("\nmedian handling nan with default axis = 0:\n",

nanmedian(arr1, axis = 0))

# using axis = 1

print("\nmedian is with default axis = 1:\n",

median(arr1, axis = 1))

print("\nmedian handling nan with default axis = 1:\n",

nanmedian(arr1, axis = 1))

输出:

median is:nan

median handling nan:3.0

median is with default axis = 0:

[ nan nan nan]

median handling nan with default axis = 0:

[ 3. 6. 6.]

median is with default axis = 1:

[ 3. nan nan nan]

median handling nan with default axis = 1:

[ 3. 4.5 4.5 4.5]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值