使用 Python Pandas 对列进行分箱 [英] Binning a column with Python Pandas

查看:52
本文介绍了使用 Python Pandas 对列进行分箱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有数值的数据框列:

I have a data frame column with numeric values:

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

我想将该列视为 bin 计数:

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

如何将结果作为带有值计数的 bin 获得?

How can I get the result as bins with their value counts?

[0, 1] bin amount
[1, 5] etc
[5, 10] etc
...

推荐答案

您可以使用 pandas.cut:

You can use 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 并聚合 尺寸:

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 方法如 Series.value_counts() 将使用所有类别,即使数据中不存在某些类别,分类操作.

Series methods like Series.value_counts() will use all categories, even if some categories are not present in the data, operations in categorical.

这篇关于使用 Python Pandas 对列进行分箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆