赞
踩
pandas.cut 小结
pandas.cut(x, bins, right=True, labels=None, retbins=False, precision=3,
include_lowest=False, duplicates='raise')
切割一维的数组,如连续的年龄segment成年龄段
x:一维的数组
bins:int,标量的序列,pandas的intervalindex
right:Boolean默认是True,表示范围包含右边缘的值否
labels:数组,bool,任意值,返回值的label
retbins:返回bins与否,当bins是标量时无效
precision:展示bins的数量
include_lowest:分开的是左闭合区间与否
duplicates:If bin edges are not unique, raise ValueError or drop non-uniques.
示例:
离散成三个平均的集和
>>>pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3)
>>>[(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0], (5.0, 7.0], (0.994, 3.0]]
Categories (3, interval[float64]): [(0.994, 3.0] < (3.0, 5.0] < (5.0, 7.0]]
>>>pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3, retbins=True)
>>>([(0.994, 3.0], (5.0, 7.0], (3.0, 5.0], (3.0, 5.0], (5.0, 7.0], (0.994, 3.0]]
Categories (3, interval[float64]): [(0.994, 3.0] < (3.0, 5.0] < (5.0, 7.0]], array([0.994, 3. , 5. , 7. ]))
这里有labels表示运算完成将数据返回的标签
>>> pd.cut(np.array([1, 7, 5, 4, 6, 3]),3, labels=["bad", "medium", "good"])
>>>[bad, good, medium, medium, good, bad]
Categories (3, object): [bad < medium < good]
如果labels的值为False,表示返回的值仅仅是原来的数字
>>> pd.cut([0, 1, 1, 2], bins=4, labels=False)
array([0, 1, 1, 3], dtype=int64)
输入一个Series返回值仍然为Series
>>> s = pd.Series(np.array([2, 4, 6, 8, 10]),index=['a', 'b', 'c', 'd', 'e'])
>>> pd.cut(s,3)
a (1.992, 4.667]
b (1.992, 4.667]
c (4.667, 7.333]
d (7.333, 10.0]
e (7.333, 10.0]
设置bins为[]
>>> s = pd.Series(np.array([2, 4, 6, 8, 10]),index=['a', 'b', 'c', 'd', 'e'])
>>> pd.cut(s, [0, 2, 4, 6, 8, 10], labels=False, retbins=True, right=False)
(a 1.0
b 2.0
c 3.0
d 4.0
e NaN
dtype: float64, array([ 0, 2, 4, 6, 8, 10]))
设置重复的duplicates等于drop删掉
>>>pd.cut(s, [0, 2, 4, 6, 10, 10], labels=False, retbins=True,right=False, duplicates='drop')
(a 1.0
b 2.0
c 3.0
d 3.0
e NaN
dtype: float64, array([ 0, 2, 4, 6, 10], dtype=int64))
自己设定划分的bins为tuple
>>> bins = pd.IntervalIndex.from_tuples([(0, 1), (2, 3), (4, 5)])
>>> pd.cut([0, 0.5, 1.5, 2.5, 4.5], bins)
[NaN, (0, 1], NaN, (2, 3], (4, 5]]
Categories (3, interval[int64]): [(0, 1] < (2, 3] < (4, 5]]
pandas.qcut(x, q, labels=None, retbins=False, precision=3, duplicates='raise')
>>>x 要进行分组的数据,数据类型为一维数组,或Series对象
>>>q 组数,即要将数据分成几组,后边举例说明
>>>labels 可以理解为组标签,这里注意标签个数要和组数相等
>>>retbins 默认为False,当为False时,返回值是Categorical类型(具有value_counts()方法),为True是返回值是元组
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。