gpt4 book ai didi

python - pandas 中更好的分箱

转载 作者:IT老高 更新时间:2023-10-28 20:52:01 32 4
gpt4 key购买 nike

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

目前,我正在这样做:

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()

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

最佳答案

也许您正在寻找 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)

产量

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

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

counts.sort_index()

产生

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

感谢 nivnivInLaw对于这种改进。


另见 Discretization and quantiling .

关于python - pandas 中更好的分箱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14451185/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com