当前位置:   article > 正文

Pandas库qcut( )与cut( )的用法与区别_pd qcut什么意思

pd qcut什么意思

1、pd.qcut()

qcut是根据这些值的频率来选择箱子的均匀间隔,即每个箱子中含有的数的数量是相同的

>>> factors = np.random.randn(9)
[ 2.12046097  0.24486218  1.64494175 -0.27307614 -2.11238291 2.15422205 -0.46832859  0.16444572  1.52536248]

>>> pd.qcut(factors, 3) #返回每个数对应的分组
[(1.525, 2.154], (-0.158, 1.525], (1.525, 2.154], (-2.113, -0.158], (-2.113, -0.158], (1.525, 2.154], (-2.113, -0.158], (-0.158, 1.525], (-0.158, 1.525]]
Categories (3, interval[float64]): [(-2.113, -0.158] < (-0.158, 1.525] < (1.525, 2.154]]

>>> pd.qcut(factors, 3).value_counts() #计算每个分组中含有的数的数量
(-2.113, -0.158]    3
(-0.158, 1.525]     3
(1.525, 2.154]      3
# 我们看到3个分组中,每个分组里面都是3个数字。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

实际用法示例:

# fare特征分段 并二值化
df['Fare_bin'] = pd.qcut(df['Fare'], 5)
print (df[['Fare_bin', 'Survived']].groupby(['Fare_bin'], as_index=False).mean().sort_values(by='Fare_bin', ascending=True))
dummies_Fare_bin = pd.get_dummies(df['Fare_bin'], prefix= 'Fare_bin')
df = pd.concat([df, dummies_Fare_bin], axis=1)

# 输出:
           Fare_bin  Survived
0    (-0.001, 7.854]  0.217877
1      (7.854, 10.5]  0.201087
2     (10.5, 21.679]  0.424419
3   (21.679, 39.688]  0.444444
4  (39.688, 512.329]  0.642045
# print函数是Fare列 被分为了5段。
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

2、pd.cut()

cut将根据值本身来选择箱子均匀间隔,即每个箱子的间距都是相同的

>>> pd.cut(factors, 3) #返回每个数对应的分组
[(0.732, 2.154], (-0.69, 0.732], (0.732, 2.154], (-0.69, 0.732], (-2.117, -0.69], (0.732, 2.154], (-0.69, 0.732], (-0.69, 0.732], (0.732, 2.154]]
Categories (3, interval[float64]): [(-2.117, -0.69] < (-0.69, 0.732] < (0.732, 2.154]]

>>> pd.cut(factors, bins=[-3,-2,-1,0,1,2,3])
[(2, 3], (0, 1], (1, 2], (-1, 0], (-3, -2], (2, 3], (-1, 0], (0, 1], (1, 2]]
Categories (6, interval[int64]): [(-3, -2] < (-2, -1] < (-1, 0] < (0, 1] (1, 2] < (2, 3]]

>>> pd.cut(factors, 3).value_counts() #计算每个分组中含有的数的数量
Categories (3, interval[float64]): [(-2.117, -0.69] < (-0.69, 0.732] < (0.732, 2.154]]
(-2.117, -0.69]    1
(-0.69, 0.732]     4
(0.732, 2.154]     4
# 我们可以看到每个分组的间距大小是一样的
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

实际用法示例:

用5个数字,分成了四段

# Age特征分段 并二值化
bins = [0, 12, 18, 65, 100]
df['Age_group'] = pd.cut(df['Age'], bins)
df['Age_group'].head(7)
  • 1
  • 2
  • 3
  • 4

输入如下图
这里写图片描述

by_age = df.groupby('Age_group')['Survived'].mean()
by_age

#输出
Age_group
(0, 12]      0.506173
(12, 18]     0.432432
(18, 65]     0.368132
(65, 100]    0.125000
Name: Survived, dtype: float64
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

备注: 我们可以把每个段当成一个特征,进行dummies

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/963697
推荐阅读
相关标签
  

闽ICP备14008679号