pandas 如何计算分位数范围内各列平均值?

rqqzpn5f  于 9个月前  发布在  其他
关注(0)|答案(1)|浏览(80)

我想计算每列的平均值,但只考虑值在分位数范围内,如20%-80%。
这就是为什么我做了,但不完整

df=pd.DataFrame({"A":[1,1,20,2,2,3,50,7,8,15,20,35,50,70],"B":[10,100,20,20,200,30,50,70,80,150,200,350,500,700]})
df
    A   B
0   1   10
1   1   100
2   20  20
3   2   20
4   2   200
5   3   30
6   50  50
7   7   70
8   8   80
9   15  150
10  20  200
11  35  350
12  50  500
13  70  70

then find q20 and 180 for each column using np.quantile()

q20=np.quantile(df,0.2,axis=0)
q20

array([ 2., 26.])

q80=np.quantile(df,0.8,axis=0)
q80

array([ 41., 260.])

字符串
现在,我如何为每列过滤q20和q80之间的值
我正在下面做,然后我得到了一个错误

mask=(a>q20)&(a<q80)

TypeError: Cannot compare a Categorical for op __gt__ with type <class 'numpy.ndarray'>.
If you want to compare values, use 'np.asarray(cat) <op> other'.


谢谢你的帮助

nwo49xxi

nwo49xxi1#

使用rankpct

out = df[df.rank(pct=True).ge(0.2) & df.rank(pct=True).le(0.8)].mean()

字符串
输出:

A     12.444444
B    110.000000
dtype: float64

相关问题