在计算四分位数范围时,我遇到了一个有趣的情况.假设我们有一个数据帧,例如:
import pandas as pd
index=pd.date_range('2014 01 01',periods=10,freq='D')
data=pd.np.random.randint(0,100,(10,5))
data = pd.DataFrame(index=index,data=data)
data
Out[90]:
0 1 2 3 4
2014-01-01 33 31 82 3 26
2014-01-02 46 59 0 34 48
2014-01-03 71 2 56 67 54
2014-01-04 90 18 71 12 2
2014-01-05 71 53 5 56 65
2014-01-06 42 78 34 54 40
2014-01-07 80 5 76 12 90
2014-01-08 60 90 84 55 78
2014-01-09 33 11 66 90 8
2014-01-10 40 8 35 36 98
# test for q1 values (this works)
data.quantile(0.25)
Out[111]:
0 40.50
1 8.75
2 34.25
3 17.50
4 29.50
# break it by inserting row of nans
data.iloc[-1] = pd.np.NaN
data.quantile(0.25)
Out[115]:
0 42
1 11
2 34
3 12
4 26
第一个四分位数可以通过取数据框中低于总体中位数的值的中值来计算,因此我们可以看到data.quantile(0.25)应该产生什么.例如
med = data.median()
q1 = data[data
q1
Out[119]:
0 37.5
1 8.0
2 19.5
3 12.0
4 17.0
似乎分位数不能提供q1等的适当表示,因为它没有很好地处理NaN值(即它在没有NaN但不与NaN一起工作).
我认为这可能不是“NaN”问题,而是分位数可能无法处理偶数数据集(即中位数必须计算为两个中心数的平均值).但是,在使用偶数行和奇数行的数据帧进行测试后,我看到分位数正确地处理了这些情况.只有当数据帧中存在NaN值时,才会出现问题.
我想使用quntile计算我的数据帧中的滚动q1 / q3值,但是,这不适用于NaN的存在.有人能为这个问题提供解决方案吗?