gpt4 book ai didi

python - 将 bin 应用于 groupby 的 pandas value_counts 产生不正确的结果

转载 作者:行者123 更新时间:2023-12-03 16:22:06 25 4
gpt4 key购买 nike

我不明白为什么 value_counts 给了我错误的答案。这是一个小例子:

In [81]: d=pd.DataFrame([[0,0],[1,100],[0,100],[2,0],[3,100],[4,100],[4,100],[4,100],[1,100],[3,100]],columns=['key','score'])

In [82]: d
Out[82]:
key score
0 0 0
1 1 100
2 0 100
3 2 0
4 3 100
5 4 100
6 4 100
7 4 100
8 1 100
9 3 100

In [83]: g=d.groupby('key')['score']
In [84]: g.value_counts(bins=[0, 20, 40, 60, 80, 100])
Out[84]:
key score
0 (-0.001, 20.0] 1
(20.0, 40.0] 1
(40.0, 60.0] 0
(60.0, 80.0] 0
(80.0, 100.0] 0
1 (20.0, 40.0] 2
(-0.001, 20.0] 0
(40.0, 60.0] 0
(60.0, 80.0] 0
(80.0, 100.0] 0
2 (-0.001, 20.0] 1
(20.0, 40.0] 0
(40.0, 60.0] 0
(60.0, 80.0] 0
(80.0, 100.0] 0
3 (20.0, 40.0] 2
(-0.001, 20.0] 0
(40.0, 60.0] 0
(60.0, 80.0] 0
(80.0, 100.0] 0
4 (20.0, 40.0] 3
(-0.001, 20.0] 0
(40.0, 60.0] 0
(60.0, 80.0] 0
(80.0, 100.0] 0
Name: score, dtype: int64


这些数据中出现的唯一值是 0 和 100。但是 value_counts 告诉我范围 (20.0,40.0] 的值最多,而 (80.0,100.0] 没有。

当然,我的真实数据有更多的值、不同的键等,但这说明了我所看到的问题。

为什么?

最佳答案

这是保持索引完整性的另一种方法。

d.groupby('key')['score'].apply(pd.Series.value_counts, bins=[0,20,40,60,80,100])

输出:
key                
0 (80.0, 100.0] 1
(-0.001, 20.0] 1
(60.0, 80.0] 0
(40.0, 60.0] 0
(20.0, 40.0] 0
1 (80.0, 100.0] 2
(60.0, 80.0] 0
(40.0, 60.0] 0
(20.0, 40.0] 0
(-0.001, 20.0] 0
2 (-0.001, 20.0] 1
(80.0, 100.0] 0
(60.0, 80.0] 0
(40.0, 60.0] 0
(20.0, 40.0] 0
3 (80.0, 100.0] 2
(60.0, 80.0] 0
(40.0, 60.0] 0
(20.0, 40.0] 0
(-0.001, 20.0] 0
4 (80.0, 100.0] 3
(60.0, 80.0] 0
(40.0, 60.0] 0
(20.0, 40.0] 0
(-0.001, 20.0] 0
Name: score, dtype: int64

关于python - 将 bin 应用于 groupby 的 pandas value_counts 产生不正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60553500/

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