Data transformation turns raw data into a clean, useful form: removing duplicates, mapping values, creating new columns, binning numbers into groups, and encoding categories for machine learning.
Prerequisites
Sample Data
import pandas as pd
df = pd.DataFrame({
'name': ['Asha', 'Ravi', 'Neha', 'Ravi', 'Aman'],
'gender': ['F', 'M', 'F', 'M', 'M'],
'age': [21, 35, 52, 35, 17],
'salary': [30000, 52000, 81000, 52000, 0]
})
Removing Duplicates
print(df.duplicated().tolist())
df = df.drop_duplicates().reset_index(drop=True)
print(len(df))
[False, False, False, True, False] 4
map and replace
df['gender'] = df['gender'].map({'F': 'Female', 'M': 'Male'})
df['salary'] = df['salary'].replace(0, pd.NA)
print(df[['gender', 'salary']])
Explanation: map converts every value using a dict (values not in the dict become NaN). replace changes only the listed values.
gender salary 0 Female 30000 1 Male 52000 2 Female 81000 3 Male <NA>
New Columns
df['age_next_year'] = df['age'] + 1
df['name_upper'] = df['name'].str.upper()
df['is_adult'] = df['age'].apply(lambda a: a >= 18)
print(df[['name', 'is_adult']])
name is_adult 0 Asha True 1 Ravi True 2 Neha True 3 Aman False
df['age'] >= 18) over apply; it is much faster on large data.Binning with cut
df['age_group'] = pd.cut(df['age'], bins=[0, 18, 35, 60, 120],
labels=['Teen', 'Young', 'Middle', 'Senior'])
print(df[['age', 'age_group']])
Explanation: Bins include the right edge by default, so 35 falls in (18, 35] = Young.
age age_group 0 21 Young 1 35 Young 2 52 Middle 3 17 Teen
Equal-Sized Groups with qcut
scores = pd.Series([10, 20, 30, 40, 50, 60, 70, 80])
print(pd.qcut(scores, 4, labels=['Q1', 'Q2', 'Q3', 'Q4']).tolist())
['Q1', 'Q1', 'Q2', 'Q2', 'Q3', 'Q3', 'Q4', 'Q4']
One-Hot Encoding
print(pd.get_dummies(df['gender'], dtype=int))
Explanation: Machine learning models need numbers. get_dummies creates one 0/1 column per category.
Female Male 0 1 0 1 0 1 2 1 0 3 0 1
Scaling
a = df['age']
df['age_minmax'] = (a - a.min()) / (a.max() - a.min())
df['age_z'] = (a - a.mean()) / a.std()
Explanation: Min-max scaling maps values to 0–1; z-score scaling gives mean 0 and standard deviation 1. In ML pipelines, use scikit-learn scalers fitted on training data.
Changing Types
df['age'] = df['age'].astype('int32')
df['gender'] = df['gender'].astype('category')
dates = pd.to_datetime(pd.Series(['2026-01-15', '2026-02-01']))
print(dates.dt.month.tolist())
[1, 2]
Common Errors
| Problem | Cause and fix |
|---|---|
| NaN after map() | Some values were not in the mapping dict. Use replace, or add the missing keys. |
ValueError: Bin labels must be one fewer than the number of bin edges |
5 edges need 4 labels. |
Practice Exercises
- Bin marks into grades A/B/C/D with cut.
- One-hot encode a city column and join it back with pd.concat(axis=1).
Interview Questions
Q: cut vs qcut?
cut uses fixed bin edges; qcut makes bins with equal counts.
Q: map vs replace?
map transforms every value (unmapped become NaN); replace changes only listed values.
Summary
Clean with drop_duplicates, map/replace values, create columns, bin with cut/qcut, encode categories with get_dummies, and scale numeric columns.
Machine Learning Tutorials, Courses and Certifications