Binning a column with pandas

Learn about the binning a column with Python pandas. By Pranit Sharma Last updated : October 06, 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.

Problem statement

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 cut function and pass the number of bins we want to create, it will divide the array or column into that specific bins.

Python Pandas - Binning a column

For this purpose, we will use pandas.cut() method. This method is used to cut the series elements into different bins. The cut function is mainly used to carry out statistical analysis.

The syntax of pandas.cut() method is:


The parameters of pandas.cut() method are:

Some of the important parameters 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.
  • left: indicates leftmost bins.

Let us understand with the help of an example,

Python program for binning a column with pandas

# 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")

# Defining bins
bins = [0, 1, 5, 10, 25, 50, 100]

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

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


The output of the above program is:

Example: Binning a column with pandasframe

Python Pandas Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.