pandas 削减 returns 个垃圾箱

pandas cut returns fewer bins

使用 pd.cut(df['series'], 100) 时,我得到 33 个独特的垃圾箱。

pd.cut(df['series'], 100).nunique()
>>> 30

这是为什么?我需要 100 个,只有切割 500 个才能得到。

pd.cut(df['series'], 500).nunique()
>>> 100

这是我描述的数据,没有缺失值

df['series'].describe()

series
count  6406.0
mean   6.041080237277553
std    12.334466838167403
min    0.03
25%    1.22
50%    2.71
75%    5.76
max    272.19

As per pandas documentation here, pd.cut 指定了多个 bin 将 return 数组范围内的多个 等宽 bin -就像(比如说系列)你在装箱。

这意味着,在创建这些等宽的bins之后,该Series中的数据将被分配到相应的bins。您应该会看到,如果您的 Series 中没有数据属于某个 bin,则不会有数据被标记为该 bin,并且该 bin 不会出现在您的数据样本中。

例如,您有一个包含 [1,2,5,7,10] 的系列,并使用 5 个分箱执行 pd.cut。结果是 (0.991,2.8] < (2.8,4.6] < (4.6,6.4] < (6.4,8.2] < (8.2, 10.0]。您可以看到 bin (2.8,4.6] 不会出现在系列中,因为其中没有值。

因此,您的分箱数据将仅包含 4 个唯一分箱。

如果您确实需要 100 个箱子(并且不关心它们是否等宽),我建议 pd.qcut。只要您的 Series 比您需要的 bin 数量长,并且您没有很多重复值,这应该 return 您指定的 bin 数量。