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

标签 python pandas

我不明白为什么 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/

相关文章:

python - pandas,计算每组的值?

regex - pandas python 中字符串的精确匹配

python - Matplotlib 图表 X 轴上的更改顺序

python - Pandas read_table() 数千 =',' 不工作

python - jupyter R 魔术到 python 脚本

python - 您可以在交互式 Altair 图中更改数据本身吗?

python - 如何使用命名的 paramstyle 占位符在带有 % 通配符的 python 变量上使用 SQL LIKE 运算符

python - Mypy 无法从文字列表中推断出项目的类型

python - 获取域中所有页面的所有内部链接

python - 加快 Pandas 应用或使用 map