我成功地用以下方法对一些数据进行了分箱:
temp['category_fare'] = pd.qcut(train['Fare'], 4)
我得到这个作为输出:
category_fare
0 (-0.001, 7.91]
1 (31.0, 512.329]
2 (7.91, 14.454]
3 (31.0, 512.329]
4 (7.91, 14.454]
.. ...
886 (7.91, 14.454]
887 (14.454, 31.0]
888 (14.454, 31.0]
889 (14.454, 31.0]
890 (-0.001, 7.91]
但我真正想要的是用一个整数替换四个类别间隔中的每一个:
(-0.001, 7.91] = 0
(7.91, 14.454] = 1
(14.454, 31.0] = 2
(31.0, 512.329] = 3
我尝试使用替换,但它不起作用。 Replace 正在尝试替换一个字符串(这就是我输入它进行替换的方式),但在我的调试器中我看到这些是间隔对象(?):
(0, Interval(-0.001, 7.91, closed='right')) (1, Interval(31.0, 512.329, closed='right'))
有没有办法将它们替换为上面相应的 int 值,甚至使用相应的 int 值创建一个新列?
我不知道如何引用间隔对象。
最佳答案
在qcut
中使用labels=False
参数:
labels : array or boolean, default None
Used as labels for the resulting bins. Must be of the same length as the resulting bins. If False, return only integer indicators of the bins.
temp['category_fare'] = pd.qcut(train['Fare'], 4, labels=False)
关于python-3.x - 将区间对象转换或替换为整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59969826/