从 pandas qcut 间隔中删除小数点(将间隔转换为整数)

Remove decimal points from pandas qcut intervals (transform intervals to integers)

我在名为example的对象的列中有很多分数。我想将这些分数分成十分位数,并为每一行分配相应的十分位数间隔。我尝试了以下方法:

import random
import pandas as pd
random.seed(420) #blazeit
example = pd.DataFrame({"Score":[random.randrange(350, 1000) for i in range(1000)]})
example["Decile"] = pd.qcut(example["Score"], 10, labels=False) + 1 # Deciles as integer from 1 to 10
example["Decile_interval"] = pd.qcut(example["Score"], 10) # Decile as interval

这给了我正在寻找的十分位数。但是,我希望 example["Decile_interval"] 中的十分位数是整数,而不是浮点数。我试过 precision=0 但它只在每个数字的末尾显示 .0

如何将区间中的浮点数转换为整数?

编辑:正如@ALollz 指出的那样,这样做会改变十分位数分布。但是,我这样做是为了演示目的,所以我并不担心。支持@JuanC 实现这一点并发布一个解决方案。

可能有更好的解决方案,但这个可行:

import numpy as np

int_categories= [pd.Interval(int(np.round(i.left)),int(np.round(i.right))) for i in example.Decile_interval.cat.categories]
example.Decile_interval.cat.categories = int_categories

输出:

0      (350, 418]
1      (680, 740]
2      (606, 680]
3      (740, 798]
4      (418, 474]
5      (418, 474]
.           .

这是我使用简单 apply 函数的解决方案:

example["Decile_interval"] = example["Decile_interval"].apply(lambda x: pd.Interval(left=int(round(x.left)), right=int(round(x.right))))