Sunday , December 6 2026
Data Transformation in Pandas - Data Science Tutorials

Data Transformation in Pandas – Data Science Tutorials

Updated: 28 November 2026Level: BeginnerReading time: about 10 minutespandas 2.x / 3.x

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

Missing Data in pandas.

Sample Data

Example
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

Example
print(df.duplicated().tolist())
df = df.drop_duplicates().reset_index(drop=True)
print(len(df))
Output
[False, False, False, True, False]
4

map and replace

Example
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.

Output
   gender salary
0  Female  30000
1    Male  52000
2  Female  81000
3    Male   <NA>

New Columns

Example
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']])
Output
   name  is_adult
0  Asha      True
1  Ravi      True
2  Neha      True
3  Aman     False
Note: Prefer vectorised code (df['age'] >= 18) over apply; it is much faster on large data.

Binning with cut

Example
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.

Output
   age age_group
0   21     Young
1   35     Young
2   52    Middle
3   17      Teen

Equal-Sized Groups with qcut

Example
scores = pd.Series([10, 20, 30, 40, 50, 60, 70, 80])
print(pd.qcut(scores, 4, labels=['Q1', 'Q2', 'Q3', 'Q4']).tolist())
Output
['Q1', 'Q1', 'Q2', 'Q2', 'Q3', 'Q3', 'Q4', 'Q4']

One-Hot Encoding

Example
print(pd.get_dummies(df['gender'], dtype=int))

Explanation: Machine learning models need numbers. get_dummies creates one 0/1 column per category.

Output
   Female  Male
0       1     0
1       0     1
2       1     0
3       0     1

Scaling

Example
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

Example
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())
Output
[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

  1. Bin marks into grades A/B/C/D with cut.
  2. 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.

Next: Hierarchical Indexing · Combining and Merging

About Machine Learning

Check Also

Exploratory Data Analysis (EDA) in Python: Step-by-Step Checklist

A step-by-step EDA checklist in pandas with tested outputs: shape, missing values, describe, value counts, groupby, correlations and charts.