gpt4 book ai didi

python - 如何使用 pd.cut 以自然的方式对数据进行分箱?

转载 作者:太空宇宙 更新时间:2023-11-03 13:58:16 25 4
gpt4 key购买 nike

假设我有一个包含 100 个 float 据点的 pandas 系列,我需要将它们放入 10 个同样宽的 bin 中,并且我需要访问第四个 bin 中的数据索引。那么我尝试的是:

import pandas as pd; import numpy as np
np.random.seed(1)
s = pd.Series(np.random.randn(100))
cut = pd.cut(s, bins=10, labels=range(10))
fourth_bin = s[cut == 4]
fourth_bin
Out[101]:
9 -0.249370
12 -0.322417
13 -0.384054
16 -0.172428
26 -0.122890
28 -0.267888
31 -0.396754
40 -0.191836
51 -0.352250
53 -0.349343
54 -0.208894
63 -0.298093
65 -0.075572
71 -0.504466
76 -0.306204
80 -0.222328
81 -0.200758
92 -0.375285
96 -0.343854
dtype: float64

这不太自然,甚至看起来有点笨拙。例如,我可以避免手动设置 labels 并直接从 pd.cut(s, bins=10) 开始吗?这样我想做一些类似的事情

s[s in pd.cut(s, bins=10).categories[4]]

因为categories是一个Interval列表,但这不起作用。

是否有更自然的方法来执行此操作,这样我就不必手动设置标签

最佳答案

pd.qcut

对于大小均匀的垃圾箱

np.random.seed(1)
s = pd.Series(np.random.randn(100))

cut = pd.qcut(s, 10, labels=False)
fourth_bin = s[cut == 4]

fourth_bin

16 -0.172428
18 0.042214
26 -0.122890
35 -0.012665
40 -0.191836
44 0.050808
54 -0.208894
65 -0.075572
81 -0.200758
97 0.043597
dtype: float64
<小时/>

pd.cut

对于均匀分布的垃圾箱

np.random.seed(1)
s = pd.Series(np.random.randn(100))

cut = pd.cut(s, 10, labels=False)
fourth_bin = s[cut == 4]
fourth_bin

9 -0.249370
12 -0.322417
13 -0.384054
16 -0.172428
26 -0.122890
28 -0.267888
31 -0.396754
40 -0.191836
51 -0.352250
53 -0.349343
54 -0.208894
63 -0.298093
65 -0.075572
71 -0.504466
76 -0.306204
80 -0.222328
81 -0.200758
92 -0.375285
96 -0.343854
dtype: float64

关于python - 如何使用 pd.cut 以自然的方式对数据进行分箱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49443658/

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