Pandas qcut() Method with Example

Learn about the Python pandas.qcut() method, its usages, explanation, and examples. By Pranit Sharma Last updated : September 30, 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.qcut() Method

We use pandas.qcut() to obtain a categorical column to make it best suited for a machine learning model, or better and more effective data analysis. The pandas.qcut() method is responsible for the quantile-based separation.

It separates the variable into equal-sized bins based on rank or based on sample quantiles. Suppose we have 1000 values for 10 quantiles, it would produce a Categorical object representing quantile partnership for each data point.

Syntax

The syntax of pandas.qcut() method is:

pandas.qcut(
    x, 
    q, 
    labels=None, 
    retbins=False, 
    precision=3, 
    duplicates='raise'
    )

Parameter(s)

The parameters of pandas.qcut() method are:

  • x: array or series
  • q: list of int or float values
  • precision: The precision at which to store and display the bins labels.
  • precision: optional, int by default
  • duplicates: If bin edges are not unique, raise ValueError or drop non-uniques.

Return Value

The return type (Categorical or Series) depends on the input.

Python pandas.qcut() Method Example

# 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 qcut method
df['bins'] = pd.qcut(df['One'],5)

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

Output

The output of the above program is:

Pandas qcut() Method Example Output

Reference: pandas.qcut()

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





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