Pandas: Data Manipulation - cut() function
cut() function
The cut() function is used to bin values into discrete intervals.
Use cut when you need to segment and sort data values into bins. This function is also useful for going from a continuous variable to a categorical variable. For example, cut could convert ages to groups of age ranges. Supports binning into an equal number of bins, or a pre-specified array of bins
Note: bins : numpy.ndarray or IntervalIndex. The computed or specified bins. Only returned when retbins=True. For scalar or sequence bins, this is an ndarray with the computed bins. If set duplicates=drop, bins will drop non-unique bin. For an IntervalIndex bins, this is equal to bins.
Syntax:
pandas.cut(x, bins, right=True, labels=None, retbins=False, precision=3, include_lowest=False, duplicates='raise')
Parameters:
Name | Description | Type | Default Value | Required / Optional |
---|---|---|---|---|
x | The input array to be binned. Must be 1-dimensional. | array-like | Required | |
bins | The criteria to bin by.
|
int, sequence of scalars, or IntervalIndex | Required | |
right | Indicates whether bins includes the rightmost edge or not. | bool, | Default: True | Required |
labels | 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. | array or bool | Optional | |
retbins | Whether to return the bins or not. Useful when bins is provided as a scalar. | bool | Default: False | Required |
precision | The precision at which to store and display the bins labels. | int | Default: 3 | Required |
include_lowest | Whether the first interval should be left-inclusive or not. | bool | Default: False | Required |
duplicates | If bin edges are not unique, raise ValueError or drop non-uniques. | Default: Raise, Drop | Optional |
Returns: out : Categorical, Series, or ndarray
An array-like object representing the respective bin for each value of x.
The type depends on the value of labels.
- True (default) : returns a Series for Series x or a Categorical for all other inputs. The values stored within are Interval dtype.
- equence of scalars : returns a Series for Series x or a Categorical for all other inputs. The values stored within are whatever the type in the sequence is.
- False : returns an ndarray of integers.
Download the Pandas DataFrame Notebooks from here.
Previous: crosstab() function
Next: qcut() function
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/pandas/cut.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics