pythonintermediate
Pandas IntervalIndex for Binning
Use IntervalIndex and pd.cut to bin continuous variables into labelled categories.
pythonPress ⌘/Ctrl + Shift + C to copy
import pandas as pd
import numpy as np
scores = np.random.randint(0, 100, 200)
bins = [0, 60, 70, 80, 90, 100]
labels = ['F', 'D', 'C', 'B', 'A']
df = pd.DataFrame({'score': scores})
df['grade'] = pd.cut(df['score'], bins=bins, labels=labels, right=True)
print(df['grade'].value_counts().sort_index())
print(df.groupby('grade')['score'].mean())Use Cases
- grading systems
- risk tiering
- feature binning
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonbeginner
Pandas Categorical Encoding for ML
One-hot encode, label encode, and ordinal encode categorical columns using pandas and scikit-learn.
Best for: ML preprocessing
#pandas#encoding
pythonintermediate
Pandas GroupBy Transform Patterns
Use groupby().transform() to compute group-level statistics and broadcast them back to row level.
Best for: feature engineering
#pandas#groupby
pythonbeginner
Pandas Datetime Component Extraction
Extract year, month, day, hour, day-of-week and other components from a datetime column.
Best for: time-based features
#pandas#datetime
pythonintermediate
Pandas Cartesian Feature Interaction
Generate pairwise feature interactions for ML by creating cross-product columns.
Best for: ML feature engineering
#pandas#feature-engineering