Pandas:数据帧.分位数axis关键字做n

2024-05-23 21:36:33 发布

您现在位置:Python中文网/ 问答频道 /正文

你知道为什么会这样吗?在

基本数据:

In  [1]: tmc_sum.head(6)
Out [1]:               1     2     3     8     9    10
         tmc                                          
         110+05759  7469  7243  7307  7347  7271  7132
         110P05759  7730  7432  7482  7559  7464  7305
         110+05095  7256  6784  6697  6646  6786  6530
         110P05095     0     0     0     0     0     0
         110+05096  6810  5226  5625  5035  5064  4734
         110P05096  6854  5041  5600  5308  5261  4747

前奏:

根据documentation of quantile,这是正确的:

^{pr2}$

它按列正确计算第5个百分位。(请注意,列数多于上面打印的六列。)

问题:

但这并不像预期的那样有效:

In  [3]: tmc_sum.quantile(0.05, axis=0)
Out [3]: 1     3347.50
         2     1882.40
         3     1933.10
         8     1755.00
         9     1554.15
         10    1747.85
         dtype: float64

它再次由列计算。尽管,根据文档,它应该按行计算。所以我倾向于这样想:

In  [4]: tmc_sum.apply(lambda x: np.percentile(x, 0.05), axis=1).head(6)
Out [4]: tmc
         110+05759    7132.2775
         110P05759    7305.3175
         110+05095    6530.2900
         110P05095       0.0000
         110+05096    4734.7525
         110P05096    4747.7350

这是预期的行为,我是遗漏了什么,还是一个bug?在


Tags: of数据indocumentationoutheadsumdtype
1条回答
网友
1楼 · 发布于 2024-05-23 21:36:33

这是0.14.0中的一个错误(axis关键字被忽略),并在0.14.1中得到了修复(请参见https://github.com/pydata/pandas/pull/7312

如果无法升级,可以使用df.T.quantile(0.5)获得所需的行为。在


顺便说一句,是axis=1的情况不正确。默认值axis=0计算不同列的分位数,axis=1计算每行的“沿列”。举个小例子,考虑一下:

In [3]: df
Out[3]:
   a  b  c
0  0  1  2
1  3  4  5

axis=0的默认值:

^{pr2}$

使用axis=1

In [5]: df.quantile(0.5, axis=1)
Out[5]:
0    1
1    4
dtype: float64

相关问题 更多 >