一、作业
Ex2:钻石数据集 现有一份关于钻石的数据集,其中 carat, cut, clarity, price 分别表示克拉重量、切割质量、纯净度和价格。
1 分别对 df.cut 在 object 类型和 category 类型下使用 nunique 函数,并比较它们的性能。
2 钻石的切割质量可以分为五个等级,由次到好分别是 Fair, Good, Very Good, Premium, Ideal ,纯净度有八个等级,由次到好分别是 I1, SI2, SI1, VS2, VS1, VVS2, VVS1, IF ,请对切割质量按照 由好到次 的顺序排序,相同切割质量的钻石,按照纯净度进行 由次到好 的排序。
3 分别采用两种不同的方法,把 cut, clarity 这两列按照 由好到次 的顺序,映射到从0到n-1的整数,其中n表示类别的个数。
4 对每克拉的价格按照分别按照分位数(q=[0.2, 0.4, 0.6, 0.8])与[1000, 3500, 5500, 18000]割点进行分箱得到五个类别 Very Low, Low, Mid, High, Very High ,并把按这两种分箱方法得到的 category 序列依次添加到原表中。
5 第4问中按照整数分箱得到的序列中,是否出现了所有的类别?如果存在没有出现的类别请把该类别删除。
6 对第4问中按照分位数分箱得到的序列,求每个样本对应所在区间的左右端点值和长度。
解答:
df = pd.read_csv('data/diamonds.csv')
df.head(3)
2.1
%timeit df.cut.nunique()
#5.58 ms ± 1.45 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)
df1 = df.cut.astype('category')
%timeit df1.nunique()
#1.8 ms ± 135 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
2.2
df.cut = df.cut.astype('category').cat.reorder_categories( [ 'Fair', 'Good', 'Very Good', 'Premium', 'Ideal' ] ,ordered=True)
df.clarity = df.clarity.astype('category').cat.reorder_categories( [ 'I1', 'SI2', 'SI1', 'VS2', 'VS1', 'VVS2', 'VVS1', 'IF'] ,ordered=True)
df.sort_values(['cut', 'clarity'], ascending=[False , True])
2.3
cut1 = df.cut.astype('category').cat.rename_categories({
'Fair': 0 , 'Good':1 , 'Very Good':2, 'Premium':3