先用cut函数确定好分层,再用groupby函数实现分布分析。
根据分析目的,将数据(定量数据)进行等距或者不等距的分组,
进行研究各组分布规律的一种分析方法。
1,功能:将数据进行离散化
pandas.cut( x , bins , right=True , labels=None , retbins=False , precision=3 , include_lowest=False,duplicates='raise')
参数说明:
#代码一:
import numpy as np
import pandas as pd
pd.cut(np.array([0.2,1.4,2.5,6.2,9.7,2.1]),3,retbins=True)
#输出结果:
([(0.19, 3.367], (0.19, 3.367], (0.19, 3.367], (3.367, 6.533], (6.533, 9.7], (0.19, 3.367]]
Categories (3, interval[float64]): [(0.19, 3.367] < (3.367, 6.533] < (6.533, 9.7]],
array([0.1905 , 3.36666667, 6.53333333, 9.7 ]))
#代码二
pd.cut(np.array([0.2,1.4,2.5,6.2,9.7,2.1]),[1,2,3],retbins=True)
#输出结果:
([NaN, (1, 2], (2, 3], NaN, NaN, (2, 3]]
Categories (2, interval[int64]): [(1, 2] < (2, 3]], array([1, 2, 3]))
#代码三:
pd.cut([1,2,3,4],4,labels=['one','two','three','four'])
#输出结果:
[one, two, three, four]
Categories (4, object): [one < two < three < four]
#cut()+groupby()组合应用实例参考代码:
import numpy
import pandas
data = pandas.read_csv(
'C:/Users/ZL/Desktop/Python/5.3/data.csv'
)
aggResult = data.groupby(
by=['年龄']
)['年龄'].agg({
'人数': numpy.size
})
data.年龄.hist()
bins = [
min(data.年龄)-1, 20, 30, 40, max(data.年龄)+1
]
labels = [
'20岁以及以下', '21岁到30岁', '31岁到40岁', '41岁以上'
]
data['年龄分层'] = pandas.cut(
data.年龄,
bins,
labels=labels
)
aggResult = data.groupby(
by=['年龄分层']
)['年龄'].agg({
'人数': numpy.size
})
pAggResult = round(
aggResult/aggResult.sum(),
2
)*100
pAggResult['人数'].map('{:,.2f}%'.format)