python - Pandas value_counts() 中的值分组

标签 python pandas count

我想从我的 pandas 数据帧创建直方图。我有 1 列,用于保存百分比值。我使用了 value_counts() 但我有太多的百分比值。 示例:

0.752        1
0.769        2
0.800        1
0.823        1
          ... 
80.365       1
84.000       1
84.615       1
85.000       10
85.714       1

我需要按相同的速率对这些值进行分组。例如 5%。 (0 - 4,999、5,000 - 9,999,...)我想要这个结果:

(示例)

0  - 4,999       24
5  - 9,999       12
10 - 14,999      30
...

最佳答案

您可以按 pd.cut() 的结果对数据进行分组方法:

In [38]: df
Out[38]:
    value  count
0   0.752      1
1  11.769      3
2  22.800      4
3  33.823      5
4  55.365      1
5  84.000      1
6  84.615      1
7  85.000     10
8  99.714      1

In [39]: df.groupby(pd.cut(df.value, bins=np.linspace(0, 100, 21)))['count'].sum().fillna(0)
Out[39]:
value
(0, 5]        1.0
(5, 10]       0.0
(10, 15]      3.0
(15, 20]      0.0
(20, 25]      4.0
(25, 30]      0.0
(30, 35]      5.0
(35, 40]      0.0
(40, 45]      0.0
(45, 50]      0.0
(50, 55]      0.0
(55, 60]      1.0
(60, 65]      0.0
(65, 70]      0.0
(70, 75]      0.0
(75, 80]      0.0
(80, 85]     12.0
(85, 90]      0.0
(90, 95]      0.0
(95, 100]     1.0
Name: count, dtype: float64

或者您可以删除 NaN:

In [40]: df.groupby(pd.cut(df.value, bins=np.linspace(0, 100, 21)))['count'].sum().dropna()
Out[40]:
value
(0, 5]        1.0
(10, 15]      3.0
(20, 25]      4.0
(30, 35]      5.0
(55, 60]      1.0
(80, 85]     12.0
(95, 100]     1.0
Name: count, dtype: float64

说明:

In [41]: pd.cut(df.value, bins=np.linspace(0, 100, 21))
Out[41]:
0       (0, 5]
1     (10, 15]
2     (20, 25]
3     (30, 35]
4     (55, 60]
5     (80, 85]
6     (80, 85]
7     (80, 85]
8    (95, 100]
Name: value, dtype: category
Categories (20, object): [(0, 5] < (5, 10] < (10, 15] < (15, 20] ... (80, 85] < (85, 90] < (90, 95] < (95, 100]]

关于python - Pandas value_counts() 中的值分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39962217/

相关文章:

Python:如何从颜色图中获取 n 种不同颜色的列表?

python - Pandas 按行读取数据

javascript - 如何在 elasticsearch 中获取每种索引类型的计数?

python - 在 Pandas 的 GroupBy 中检查负滚动窗口中的条件

php - Mysql 函数 count() 逐行计数

arrays - 在 Swift 中确定多维数组的大小

python正则表达式向前看正+负

python - pip freeze 不显示包

python - 有没有办法在 Python 中检查函数的签名?

python - 为什么 CSV 文件将第一列加载为 dtype64[ns],但将 txt 作为对象加载