Introduction
Binning helps group continuous numbers into categories. This makes data easier to understand and analyze.
Binning helps group continuous numbers into categories. This makes data easier to understand and analyze.
pandas.cut(x, bins, labels=None, right=True, include_lowest=False)
x is the continuous data you want to bin.
bins defines the edges of the groups.
import pandas as pd ages = [22, 35, 58, 45, 18] bins = [0, 30, 60] categories = pd.cut(ages, bins) print(categories)
labels = ['Young', 'Old'] categories = pd.cut(ages, bins, labels=labels) print(categories)
categories = pd.cut(ages, bins, right=False, include_lowest=True) print(categories)
This program groups exam scores into letter grades using bins.
import pandas as pd # Sample continuous data: exam scores scores = [55, 67, 89, 45, 72, 90, 33, 78, 84, 60] # Define bins for grades bins = [0, 60, 70, 80, 90, 100] labels = ['F', 'D', 'C', 'B', 'A'] # Bin the scores into grade categories grade_categories = pd.cut(scores, bins=bins, labels=labels, include_lowest=True) # Create a DataFrame to show scores and their grades df = pd.DataFrame({'Score': scores, 'Grade': grade_categories}) print(df)
Binning changes continuous data into categories, which can lose some detail.
Choose bins carefully to make meaningful groups.
Use include_lowest=True to include the smallest value in the first bin.
Binning groups continuous numbers into categories.
Use pandas.cut() with bins and optional labels.
Binning helps simplify data and prepare it for analysis.
data into 3 equal-width bins?pd.cut() with parameters: data and bins.bins=3 specifies 3 equal-width bins correctly.print(binned.value_counts())?
import pandas as pd values = [1, 2, 3, 4, 5, 6] binned = pd.cut(values, bins=[0, 2, 4, 6]) print(binned.value_counts())
data into 4 bins?
import pandas as pd bins = [0, 10, 20, 30] binned = pd.cut(data, bins=4) print(binned)
data which is not defined, causing a NameError.pd.cut(data, bins=4) is valid syntax if data exists; the primary issue is the missing definition.Pass the test and this pattern moves unknown