Python 更好的 Pandas 分箱

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14451185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:32:48  来源:igfitidea点击:

Better binning in pandas

pythonpandasbinning

提问by monkut

I've got a data frame and want to filter or bin by a range of values and then get the counts of values in each bin.

我有一个数据框,想按一系列值进行过滤或分箱,然后获取每个分箱中的值计数。

Currently, I'm doing this:

目前,我正在这样做:

x = 5
y = 17
z = 33
filter_values = [x, y, z]
filtered_a = df[df.filtercol <= x]
a_count = filtered_a.filtercol.count()

filtered_b = df[df.filtercol > x]
filtered_b = filtered_b[filtered_b <= y]
b_count = filtered_b.filtercol.count()

filtered_c = df[df.filtercol > y]
c_count = filtered_c.filtercol.count()

But is there a more concise way to accomplish the same thing?

但是有没有更简洁的方法来完成同样的事情?

采纳答案by unutbu

Perhaps you are looking for pandas.cut:

也许您正在寻找pandas.cut

import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(50), columns=['filtercol'])
filter_values = [0, 5, 17, 33]   
out = pd.cut(df.filtercol, bins=filter_values)
counts = pd.value_counts(out)
# counts is a Series
print(counts)

yields

产量

(17, 33]    16
(5, 17]     12
(0, 5]       5


To reorder the result so the bin ranges appear in order, you could use

要对结果重新排序以使 bin 范围按顺序显示,您可以使用

counts.sort_index()

which yields

这产生

(0, 5]       5
(5, 17]     12
(17, 33]    16

Thanks to nivnivand InLawfor this improvement.

感谢nivnivInLaw的改进。



See also Discretization and quantiling.

另请参阅离散化和量化