pandas.cut — pandas 2.2.2 documentation (2024)

pandas.cut(x, bins, right=True, labels=None, retbins=False, precision=3, include_lowest=False, duplicates='raise', ordered=True)[source]#

Bin values into discrete intervals.

Use cut when you need to segment and sort data values into bins. Thisfunction is also useful for going from a continuous variable to acategorical variable. For example, cut could convert ages to groups ofa*ge ranges. Supports binning into an equal number of bins, or apre-specified array of bins.

Parameters:
xarray-like

The input array to be binned. Must be 1-dimensional.

binsint, sequence of scalars, or IntervalIndex

The criteria to bin by.

  • int : Defines the number of equal-width bins in the range of x. Therange of x is extended by .1% on each side to include the minimumand maximum values of x.

  • sequence of scalars : Defines the bin edges allowing for non-uniformwidth. No extension of the range of x is done.

  • IntervalIndex : Defines the exact bins to be used. Note thatIntervalIndex for bins must be non-overlapping.

rightbool, default True

Indicates whether bins includes the rightmost edge or not. Ifright == True (the default), then the bins [1, 2, 3, 4]indicate (1,2], (2,3], (3,4]. This argument is ignored whenbins is an IntervalIndex.

labelsarray or False, default None

Specifies the labels for the returned bins. Must be the same length asthe resulting bins. If False, returns only integer indicators of thebins. This affects the type of the output container (see below).This argument is ignored when bins is an IntervalIndex. If True,raises an error. When ordered=False, labels must be provided.

retbinsbool, default False

Whether to return the bins or not. Useful when bins is providedas a scalar.

precisionint, default 3

The precision at which to store and display the bins labels.

include_lowestbool, default False

Whether the first interval should be left-inclusive or not.

duplicates{default ‘raise’, ‘drop’}, optional

If bin edges are not unique, raise ValueError or drop non-uniques.

orderedbool, default True

Whether the labels are ordered or not. Applies to returned typesCategorical and Series (with Categorical dtype). If True,the resulting categorical will be ordered. If False, the resultingcategorical will be unordered (labels must be provided).

Returns:
outCategorical, Series, or ndarray

An array-like object representing the respective bin for each valueof x. The type depends on the value of labels.

  • None (default) : returns a Series for Series x or aCategorical for all other inputs. The values stored withinare Interval dtype.

  • sequence of scalars : returns a Series for Series x or aCategorical for all other inputs. The values stored withinare whatever the type in the sequence is.

  • False : returns an ndarray of integers.

binsnumpy.ndarray or IntervalIndex.

The computed or specified bins. Only returned when retbins=True.For scalar or sequence bins, this is an ndarray with the computedbins. If set duplicates=drop, bins will drop non-unique bin. Foran IntervalIndex bins, this is equal to bins.

See also

qcut

Discretize variable into equal-sized buckets based on rank or based on sample quantiles.

Categorical

Array type for storing data that come from a fixed set of values.

Series

One-dimensional array with axis labels (including time series).

IntervalIndex

Immutable Index implementing an ordered, sliceable set.

Notes

Any NA values will be NA in the result. Out of bounds values will be NA inthe resulting Series or Categorical object.

Reference the user guide for more examples.

Examples

Discretize into three equal-sized bins.

>>> 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], ...Categories (3, interval[float64, right]): [(0.994, 3.0] < (3.0, 5.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], ...Categories (3, interval[float64, right]): [(0.994, 3.0] < (3.0, 5.0] ...array([0.994, 3. , 5. , 7. ]))

Discovers the same bins, but assign them specific labels. Notice thatthe returned Categorical’s categories are labels and is ordered.

>>> 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']

ordered=False will result in unordered categories when labels are passed.This parameter can be used to allow non-unique labels:

>>> pd.cut(np.array([1, 7, 5, 4, 6, 3]), 3,...  labels=["B", "A", "B"], ordered=False)['B', 'B', 'A', 'A', 'B', 'B']Categories (2, object): ['A', 'B']

labels=False implies you just want the bins back.

>>> pd.cut([0, 1, 1, 2], bins=4, labels=False)array([0, 1, 1, 3])

Passing a Series as an input returns a Series with categorical dtype:

>>> 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]dtype: categoryCategories (3, interval[float64, right]): [(1.992, 4.667] < (4.667, ...

Passing a Series as an input returns a Series with mapping value.It is used to map numerically to intervals based on 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]))

Use drop optional when bins is not unique

>>> 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]))

Passing an IntervalIndex for bins results in those categories exactly.Notice that values not covered by the IntervalIndex are set to NaN. 0is to the left of the first bin (which is closed on the right), and 1.5falls between two bins.

>>> 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.0, 1.0], NaN, (2.0, 3.0], (4.0, 5.0]]Categories (3, interval[int64, right]): [(0, 1] < (2, 3] < (4, 5]]
pandas.cut — pandas 2.2.2 documentation (2024)
Top Articles
Latest Posts
Article information

Author: Horacio Brakus JD

Last Updated:

Views: 5837

Rating: 4 / 5 (71 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Horacio Brakus JD

Birthday: 1999-08-21

Address: Apt. 524 43384 Minnie Prairie, South Edda, MA 62804

Phone: +5931039998219

Job: Sales Strategist

Hobby: Sculling, Kitesurfing, Orienteering, Painting, Computer programming, Creative writing, Scuba diving

Introduction: My name is Horacio Brakus JD, I am a lively, splendid, jolly, vivacious, vast, cheerful, agreeable person who loves writing and wants to share my knowledge and understanding with you.