python-3.x - 将区间对象转换或替换为整数值

标签 python-3.x pandas

我成功地用以下方法对一些数据进行了分箱:

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/

相关文章:

python - 如何在其他列满足特定条件的情况下替换 NaN 值?

python ->属性错误 : 'list' object has no attribute 'lower' (in a lowercase dataframe)

python - Pandas Python : sort dataframe but don't include given row

python - 循环转置和连接数据帧列表

python - 如何从包含年份和月份的单个日期列中为每年创建一个列?

python - 如何在条件 f 字符串中应用浮点精度(类型说明符)?

python - 从一个很长的迭代中随机抽样,在 python 中

python-3.x - ModuleNotFoundError : No module named 'sklearn.cluster._k_means' scikit-learn 0. 22 与 0.22.1

python - 为什么我的正向先行断言会消耗字符串并且无法正确匹配?

python - 如何处理 "Incompatible return value type (got overloaded function)"问题