使用pandas对列进行分组

197

我有一个包含数字值的数据框列:

df['percentage'].head()
46.5
44.2
100.0
42.12

我希望看到列的分组统计

bins = [0, 1, 5, 10, 25, 50, 100]

如何将结果作为其值计数的条形图呈现?

[0, 1] bin amount
[1, 5] etc
[5, 10] etc
...
4个回答

350
你可以使用 pandas.cut
bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
   percentage     binned
0       46.50   (25, 50]
1       44.20   (25, 50]
2      100.00  (50, 100]
3       42.12   (25, 50]

bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
   percentage binned
0       46.50      5
1       44.20      5
2      100.00      6
3       42.12      5

或者 numpy.searchsorted:
bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
   percentage  binned
0       46.50       5
1       44.20       5
2      100.00       6
3       42.12       5

然后使用value_countsgroupby并聚合size

s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50]     3
(50, 100]    1
(10, 25]     0
(5, 10]      0
(1, 5]       0
(0, 1]       0
Name: percentage, dtype: int64

s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1]       0
(1, 5]       0
(5, 10]      0
(10, 25]     0
(25, 50]     3
(50, 100]    1
dtype: int64

默认情况下,cut 返回 categorical分类操作。像Series.value_counts()这样的Series方法将使用所有类别,即使某些类别在数据中不存在。

2
@qqqwww - 不确定是否理解,你认为是 qcut 吗?链接 - jezrael
@jezreal,你能建议如何计算每个箱的平均值吗? - Ayan Mitra
2
@AyanMitra - 你认为 df.groupby(pd.cut(df['percentage'], bins=bins)).mean() 可以吗? - jezrael
1
谢谢,这个答案对我很有帮助 :) - Stav Cohen
有没有办法找到班级表中给定数据的平均值(而不是计数的平均值)? - Say OL
显示剩余2条评论

24

使用Numba模块进行加速。

在大型数据集(超过500k)上,pd.cut对于分箱数据可能会非常慢。

我使用Numba编写了自己的函数进行及时编译,速度快约六倍:

from numba import njit

@njit
def cut(arr):
    bins = np.empty(arr.shape[0])
    for idx, x in enumerate(arr):
        if (x >= 0) & (x < 1):
            bins[idx] = 1
        elif (x >= 1) & (x < 5):
            bins[idx] = 2
        elif (x >= 5) & (x < 10):
            bins[idx] = 3
        elif (x >= 10) & (x < 25):
            bins[idx] = 4
        elif (x >= 25) & (x < 50):
            bins[idx] = 5
        elif (x >= 50) & (x < 100):
            bins[idx] = 6
        else:
            bins[idx] = 7

    return bins
cut(df['percentage'].to_numpy())

# array([5., 5., 7., 5.])

可选项:您还可以将其映射为字符串类型的箱:

a = cut(df['percentage'].to_numpy())

conversion_dict = {1: 'bin1',
                   2: 'bin2',
                   3: 'bin3',
                   4: 'bin4',
                   5: 'bin5',
                   6: 'bin6',
                   7: 'bin7'}

bins = list(map(conversion_dict.get, a))

# ['bin5', 'bin5', 'bin7', 'bin5']

速度比较:

# Create a dataframe of 8 million rows for testing
dfbig = pd.concat([df]*2000000, ignore_index=True)

dfbig.shape

# (8000000, 1)
%%timeit
cut(dfbig['percentage'].to_numpy())

# 38 ms ± 616 µs per loop (mean ± standard deviation of 7 runs, 10 loops each)
%%timeit
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
pd.cut(dfbig['percentage'], bins=bins, labels=labels)

# 215 ms ± 9.76 ms per loop (mean ± standard deviation of 7 runs, 10 loops each)

真的很酷,从未听说过numba。它听起来非常有趣! - SimAzz

2

使用Numpy方便快捷

np.digitize是一个方便且快速的选项:

import pandas as pd
import numpy as np

df = pd.DataFrame({'x': [1,2,3,4,5]})
df['y'] = np.digitize(df['x'], bins=[3,5]) # convert column to bin

print(df)

返回

   x  y
0  1  0
1  2  0
2  3  1
3  4  1
4  5  2

1

我们也可以使用 np.select

bins = [0, 1, 5, 10, 25, 50, 100]
df['groups'] = (np.select([df['percentage'].between(i, j, inclusive='right') 
                           for i,j in zip(bins, bins[1:])], 
                          [1, 2, 3, 4, 5, 6]))

输出:

   percentage  groups
0       46.50       5
1       44.20       5
2      100.00       6
3       42.12       5

我很想看看这个解决方案在速度上与切割解决方案相比如何。 - goryh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接