pandas.cut 函数在假设为 0 时给了我负值

pandas.cut function gave me negative values when it is suppose to be 0

我很困惑为什么我的 pd.cut 函数给我的起始间隔是负值。 我剪切的列的最小值为 0。因此,我希望我的 pd.cut 函数将我的第一个间隔抛出为 (0,18) 而不是 (-0.18,18)。

我已将精度设置更改为 0。但是,这只会使我的起始间隔为 (-0.0,18)。

当我解析到我的 pd.cut 函数中的列是整数时,为什么我的区间都是浮点数?

感谢所有帮助。谢谢。

如评论中所述,您要求 cut 自动为您定义 bins,默认情况下它们是等宽的,这意味着负边界是可能的。

如果您希望保留自动分箱,您可以在之后手动修改间隔。以下是仅第一个“不正确”间隔的示例,使用 cat.rename_categories:

np.random.seed(0)
s = pd.Series(np.random.randint(-10,100,size=100)).clip(lower=0)
s_cut = pd.cut(s, bins=10)
print(s_cut.cat.categories)

first_I = s_cut.cat.categories[0]
new_I = pd.Interval(0, first_I.right)
s_cut = s_cut.cat.rename_categories({first_I: new_I})
print(s_cut.cat.categories)

输出:

# before
IntervalIndex([(-0.095, 9.5], (9.5, 19.0], (19.0, 28.5], ...)

# after
IntervalIndex([(0.0, 9.5], (9.5, 19.0], (19.0, 28.5], ...)