How to use pandas cut() method?

Learn, how to use pandas cut() method? By Pranit Sharma Last updated : October 03, 2023

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

Python pandas.cut() Method

The pandas.cut() method is used to cut the series of elements into different parts. The cut function is mainly used to perform statistical analysis.

Suppose, we have a DataFrame with multiple columns now each of the columns of this DataFrame will act as a series of an array where if we apply the pandas.cut() method and pass the number of bins we want to create, it will divide the array or column into that specific bins.

Syntax

The syntax of pandas.cut() method is:

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

Parameter(s)

The patameters of pandas.cut() method are:

  • X: The array or series whose partitions have to be made.
  • bins: Number of bins in which the array or series has to be divided.
  • right: Indicates rightmost bins.
  • levels: Specifies the labels for the returned bins.
  • retbins: Whether to return the bins or not.
  • precision: The precision at which to store and display the bins labels.
  • include_lowest: Whether the first interval should be left-inclusive or not.
  • duplicates: If bin edges are not unique, raise ValueError or drop non-uniques.
  • ordered: Whether the labels are ordered or not.

Let us understand with the help of an example,

Python Example of pandas.cut() Method

# Importing pandas package
import pandas as pd

# Creating two dictionaries
d1 = {'One':[i for i in range(10,100,10)]}

# Creating DataFrame
df = pd.DataFrame(d1)

# Display the DataFrame
print("Original DataFrame:\n",df,"\n")

# Using cut method
df['bins'] = pd.cut(df['One'],5)

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output

The output of the above program is:

Example: How to use pandas cut() method

Reference: pandas.cut

Python Pandas Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.