gpt4 book ai didi

python - 为什么 Pandas qcut 给我大小不等的垃圾箱?

转载 作者:行者123 更新时间:2023-12-03 13:40:22 28 4
gpt4 key购买 nike

Pandas docs关于 qcut 函数有这样的说法:

Discretize variable into equal-sized buckets based on rank or based on sample quantiles.



所以我希望这段代码能给我 4 个箱子,每个箱子有 10 个值:
import numpy as np
import pandas as pd

np.random.seed(4242)

y = pd.Series(np.random.randint(low=1, high=10, size=40))
quartiles = pd.qcut(y, 4, labels=['1st', '2nd', '3rd', '4th'])

print('Quartiles:')
print(quartiles.value_counts(sort=False))

y.groupby(quartiles).agg(['count', 'mean']).plot(kind='bar');

但是我得到了这个:
Quartiles:
1st 14
2nd 6
3rd 11
4th 9
dtype: int64

graph

我在这里做错了什么?

最佳答案

发生这种情况的原因是因为 python 不知道如何处理“边界线”情况,即可能很容易满足第一和第二四分位数的记录。对您的代码进行简单的调整将产生所需的结果:

import numpy as np
import pandas as pd

np.random.seed(4242)

y = pd.Series(np.random.randint(low=1, high=10, size=40))
quartiles = pd.qcut(y.rank(method = 'first'), 4, labels=['1st', '2nd', '3rd', '4th'])

print('Quartiles:')
print(quartiles.value_counts(sort=False))

y.groupby(quartiles).agg(['count', 'mean']).plot(kind='bar');
通过使用 rank() 说明 python 使用的方法函数,我们为 python 提供了一种处理跨越多个 bin 的记录的清晰方法。在这种情况下,我使用了 (method = 'first')作为 rank() 的参数功能。
我得到的输出如下:
Quartiles:
1st 10
2nd 10
3rd 10
4th 10
dtype: int64

关于python - 为什么 Pandas qcut 给我大小不等的垃圾箱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44636160/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com