连续变量离散化——cut()函数

cut()函数应用:

pd.cut(x, bins, right=True, labels=None, retbins=False, precision=3, include_lowest=False, duplicates='raise')
将连续型变量的每个值分配到指定的离散区间;

parameters
----------
x : array-like
    要分箱的数组,一维。
bins : 整数、标量序列, or pandas.IntervalIndex
    分箱标准。
    * 整数:将x分成均等的整数份。
    * 标量序列:将x分成不均等的几份。
    * IntervalIndex : Defines the exact bins to be used.

right : bool, default True
    是否包括右侧端点
labels : array or bool, optional
    指定分箱后数据标签。Specifies the labels for the returned bins. Must be the same length as
    the resulting bins. If False, returns only integer indicators of the
    bins. This affects the type of the output container (see below).
    This argument is ignored when `bins` is an IntervalIndex.
include_lowest:包括左端最小值,布尔值。

返回:

labels;intervals

注:

缺省值和超出范围的值归到NA类。

例子:

1.将x分到3个均等大小的箱中,label默认离散区间。

pd.cut([1,7,5,4,6,3], 3)
Out[16]: 
[(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]]

2.将x分到3个均等大小的箱中,label=False,用序号代替区间。

pd.cut([1,7,5,4,6,3], 3,labels=False)
Out[17]: array([0, 2, 1, 1, 2, 0])

猜你喜欢

转载自blog.csdn.net/zs15321583801/article/details/81325562
今日推荐