日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

python利用pd.cut()和pd.qcut()對數(shù)據(jù)進行分箱操作_python

作者:cbright63 ? 更新時間: 2022-08-07 編程語言

1.cut()可以實現(xiàn)類似于對成績進行優(yōu)良統(tǒng)計的功能,來看代碼示例。

假如我們有一組學生成績,我們需要將這些成績分為不及格(0-59)、及格(60-70)、良(71-85)、優(yōu)(86-100)這幾組。這時候可以用到cut()

import numpy as np
import pandas as pd

# 我們先給 scores傳入30個從0到100隨機的數(shù)
scores = np.random.uniform(0,100,size=30)

# 然后使用 np.round()函數(shù)控制數(shù)據(jù)精度
scores = np.round(scores,1)

# 指定分箱的區(qū)間
grades = [0,59,70,85,100]

cuts = pd.cut(scores,grades)
print('\nscores:')
print(scores)
print('\ncuts:')
print(cuts)
# 我們還可以計算出每個箱子中有多少個數(shù)據(jù)
print('\ncats.value_counts:')
print(pd.value_counts(cuts))

======output:======

scores:
[ 6. ?50.8 80.2 22.1 60.1 75.1 30.8 50.8 81.6 17.4 13.4 24.3 67.3 84.4
?63.4 21.3 17.2 ?3.7 40.1 12.4 15.7 23.1 67.4 94.8 72.6 12.8 81. ?82.
?70.2 54.1]

cuts:
[(0, 59], (0, 59], (70, 85], (0, 59], (59, 70], ..., (0, 59], (70, 85], (70, 85], (70, 85], (0, 59]]
Length: 30
Categories (4, interval[int64]): [(0, 59] < (59, 70] < (70, 85] < (85, 100]]

cuts.value_counts:
(0, 59] ? ? ?17
(70, 85] ? ? ?8
(59, 70] ? ? ?4
(85, 100] ? ? 1
dtype: int64

默認情況下,cat()的區(qū)間劃分是左開右閉,可以傳遞right=False來改變哪一邊是封閉的

代碼示例:

cuts = pd.cut(scores,grades,right=False)

也可以通過向labels選項傳遞一個列表或數(shù)組來傳入自定義的箱名

代碼示例:

group_names = ['不及格','及格','良','優(yōu)秀']
cuts = pd.cut(scores,grades,labels=group_names)

當我們不需要自定義劃分區(qū)間時,而是需要根據(jù)數(shù)據(jù)中最大值和最小值計算出等長的箱子。

代碼示例:

# 將成績均勻的分在四個箱子中,precision=2的選項將精度控制在兩位
cuts = pd.cut(scores,4,precision=2)

2.qcut()可以生成指定的箱子數(shù),然后使每個箱子都具有相同數(shù)量的數(shù)據(jù)

代碼示例:

import numpy as np
import pandas as pd

# 正態(tài)分布
data = np.random.randn(100)

# 分四個箱子
cuts = pd.qcut(data,4)

print('\ncuts:')
print(cuts)
print('\ncuts.value_counts:')
print(pd.value_counts(cuts))


======output:======

cuts:
[(-0.745, -0.0723], (0.889, 2.834], (-0.745, -0.0723], (0.889, 2.834], (0.889, 2.834], ..., (-0.745, -0.0723], (-0.0723, 0.889], (-3.1599999999999997, -0.745], (-0.745, -0.0723], (-0.0723, 0.889]]
Length: 100
Categories (4, interval[float64]): [(-3.1599999999999997, -0.745] < (-0.745, -0.0723] < (-0.0723, 0.889] <
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? (0.889, 2.834]]

cuts.value_counts:
(0.889, 2.834] ? ? ? ? ? ? ? ? ? 25
(-0.0723, 0.889] ? ? ? ? ? ? ? ? 25
(-0.745, -0.0723] ? ? ? ? ? ? ? ?25
(-3.1599999999999997, -0.745] ? ?25
dtype: int64

原文鏈接:https://blog.csdn.net/marioivy/article/details/96766913

欄目分類
最近更新