Mathew K Analytics

Lesson 45 · Mastering Pandas

Optimizing Large Datasets in Pandas: Efficient Techniques for Data Processing

Working with big data in pandas is powerful, but optimizing for speed and memory is key. In this lesson, we will: Load real-world data. Explore efficient…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Hands-On: Optimizing Large Datasets in Pandas#

Working with big data in pandas is powerful, but optimizing for speed and memory is key.

In this lesson, we will:

  • Load real-world data.
  • Explore efficient data types.
  • Use chunking to read large files.
  • Apply vectorized operations.
  • Save memory with categories.
  • Handle missing data cleverly.
  • Filter efficiently.
  • Aggregate and group smartly.
  • Merge and join big datasets.
  • Reshape and pivot quickly.
  • Use time-series efficiently.
  • Visualize with pandas built-ins.
  • Practice with a mini Titanic challenge.
  • Review best practices and speed tips.
  • Tackle troubleshooting tricks.
  • Try a hands-on challenge.

Lets begin optimizing your pandas skills!

# Suppress warnings before anything else
import warnings; warnings.filterwarnings("ignore")
import numpy as np
np.random.seed(42)
# Data setup (Titanic Dataset)
import pandas as pd
url = 'https://raw.githubusercontent.com/datasciencedojo/datasets/master/titanic.csv'
df = pd.read_csv(url)
print(df.shape)
print(df.head(3))
(891, 12)
   PassengerId  Survived  Pclass  \
0            1         0       3   
1            2         1       1   
2            3         1       3   

                                                Name     Sex   Age  SibSp  \
0                            Braund, Mr. Owen Harris    male  22.0      1   
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  female  38.0      1   
2                             Heikkinen, Miss. Laina  female  26.0      0   

   Parch            Ticket     Fare Cabin Embarked  
0      0         A/5 21171   7.2500   NaN        S  
1      0          PC 17599  71.2833   C85        C  
2      0  STON/O2. 3101282   7.9250   NaN        S  

Why Optimize?#

Big datasets can make pandas slow or crash with memory errors.

  • Optimizing lets you work with more data without specialized hardware.
  • Good habits prevent frustrating errors down the line.
# Exploring memory usage
print(df.info(memory_usage="deep"))
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 12 columns):
 #   Column       Non-Null Count  Dtype  
---  ------       --------------  -----  
 0   PassengerId  891 non-null    int64  
 1   Survived     891 non-null    int64  
 2   Pclass       891 non-null    int64  
 3   Name         891 non-null    object 
 4   Sex          891 non-null    object 
 5   Age          714 non-null    float64
 6   SibSp        891 non-null    int64  
 7   Parch        891 non-null    int64  
 8   Ticket       891 non-null    object 
 9   Fare         891 non-null    float64
 10  Cabin        204 non-null    object 
 11  Embarked     889 non-null    object 
dtypes: float64(2), int64(5), object(5)
memory usage: 285.6 KB
None
# Convert object columns to categoricals
for col in ['Sex', 'Embarked', 'Cabin', 'Ticket']:
    df[col] = df[col].astype('category')
print(df.dtypes[['Sex', 'Embarked', 'Cabin', 'Ticket']])
Sex         category
Embarked    category
Cabin       category
Ticket      category
dtype: object
# Memory usage after conversion
print(df.info(memory_usage="deep"))
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 12 columns):
 #   Column       Non-Null Count  Dtype   
---  ------       --------------  -----   
 0   PassengerId  891 non-null    int64   
 1   Survived     891 non-null    int64   
 2   Pclass       891 non-null    int64   
 3   Name         891 non-null    object  
 4   Sex          891 non-null    category
 5   Age          714 non-null    float64 
 6   SibSp        891 non-null    int64   
 7   Parch        891 non-null    int64   
 8   Ticket       891 non-null    category
 9   Fare         891 non-null    float64 
 10  Cabin        204 non-null    category
 11  Embarked     889 non-null    category
dtypes: category(4), float64(2), int64(5), object(1)
memory usage: 185.5 KB
None
# Downcast numerical types to save space
df['Age'] = pd.to_numeric(df['Age'], downcast='float')
df['Fare'] = pd.to_numeric(df['Fare'], downcast='float')
df['Pclass'] = pd.to_numeric(df['Pclass'], downcast='integer')
print(df[['Age', 'Fare', 'Pclass']].dtypes)
Age       float32
Fare      float32
Pclass       int8
dtype: object
# Handling missing values efficiently
print(df.isnull().sum())

# Fill missing ages with the median age
df['Age'].fillna(df['Age'].median(), inplace=True)
PassengerId      0
Survived         0
Pclass           0
Name             0
Sex              0
Age            177
SibSp            0
Parch            0
Ticket           0
Fare             0
Cabin          687
Embarked         2
dtype: int64
# Fast filtering with query
adults = df.query('Age >= 18')
print(adults[['Name', 'Age']].head())
                                                Name   Age
0                            Braund, Mr. Owen Harris  22.0
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  38.0
2                             Heikkinen, Miss. Laina  26.0
3       Futrelle, Mrs. Jacques Heath (Lily May Peel)  35.0
4                           Allen, Mr. William Henry  35.0
# Using vectorized operations instead of loops
df['FamilySize'] = df['SibSp'] + df['Parch'] + 1
# Use chunking to load large CSVs (simulate with a small chunk)
chunk_iter = pd.read_csv(url, chunksize=100)
first_chunk = next(chunk_iter)
print(first_chunk.head(2))
   PassengerId  Survived  Pclass  \
0            1         0       3   
1            2         1       1   

                                                Name     Sex   Age  SibSp  \
0                            Braund, Mr. Owen Harris    male  22.0      1   
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  female  38.0      1   

   Parch     Ticket     Fare Cabin Embarked  
0      0  A/5 21171   7.2500   NaN        S  
1      0   PC 17599  71.2833   C85        C  

Grouping and Aggregation for Big Datasets#

Pandas groupby gives quick summaries, even for millions of rows. We use it to answer questions like 'Average fare by class?' or 'Survival rate by family size.'

# Efficient groupby and aggregation
class_fare = df.groupby('Pclass')['Fare'].mean()
print(class_fare)
Pclass
1    84.154686
2    20.662184
3    13.675550
Name: Fare, dtype: float32
# Optimized merging: Join Titanic with itself on FamilySize
df_join = pd.merge(df, df, on='FamilySize', suffixes=('_a', '_b'))
print(df_join[['Name_a', 'FamilySize', 'Name_b']].head(2))
                    Name_a  FamilySize  \
0  Braund, Mr. Owen Harris           2   
1  Braund, Mr. Owen Harris           2   

                                              Name_b  
0                            Braund, Mr. Owen Harris  
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  
# Pivoting for wide-to-long reshaping
pvt = df.pivot_table(index='FamilySize', values='Survived', aggfunc='mean')
print(pvt.head())
            Survived
FamilySize          
1           0.303538
2           0.552795
3           0.578431
4           0.724138
5           0.200000
# Speed up string operations using .str methods
df['NameStart'] = df['Name'].str.split(',').str[0]
# Time series: Set up with random sample data
import numpy as np
dates = pd.date_range('2020-01-01', periods=df.shape[0])
df['FakeDate'] = dates
df.set_index('FakeDate', inplace=True)
df['Survived'].resample('M').mean().plot(title='Monthly average survival rate')
<Axes: title={'center': 'Monthly average survival rate'}, xlabel='FakeDate'>
No description has been provided for this image

Quick Visualization - Value Counts Barplot#

Pandas can quickly plot bar charts for categorical breakdowns. We do not always need a separate library for basic graphs.

# Plot survival by class
df['Survived'].groupby(df['Pclass']).mean().plot(kind='bar', title='Survival Rate by Class')
<Axes: title={'center': 'Survival Rate by Class'}, xlabel='Pclass'>
No description has been provided for this image
# Mini-challenge: How many people older than 50 survived?
survived_over_50 = df[(df['Age'] > 50) & (df['Survived'] == 1)]
print(len(survived_over_50))
22

Best Practice Tips#

  • Always check dtypes to save memory.
  • Use categories for repeated text.
  • Downcast numbers when safe.
  • Fill missing data up front.
  • Use vectorized and built-in methods.
  • Query and filter before merging or plotting.
  • Visualize only what you need.

These habits make pandas work smoother and faster.

# Common error: Trying to load too much data at once
try:
    giant_df = pd.read_csv(url, nrows=12_000_000)
except Exception as e:
    print('Error:', str(e))
    
# Quick Challenge: Filter all children (under 16) in 1 line
children = df[df['Age'] < 16]
print(children[['Name', 'Age']].head())
                                            Name   Age
FakeDate                                              
2020-01-08        Palsson, Master. Gosta Leonard   2.0
2020-01-10   Nasser, Mrs. Nicholas (Adele Achem)  14.0
2020-01-11       Sandstrom, Miss. Marguerite Rut   4.0
2020-01-15  Vestrom, Miss. Hulda Amanda Adolfina  14.0
2020-01-17                  Rice, Master. Eugene   2.0

Lesson Recap#

Today you learned how to:

  • Analyze memory use in pandas.
  • Use the right dtypes for speed and space.
  • Load large files safely with chunking.
  • Leverage vectorized operations.
  • Aggregate and merge efficiently.
  • Pivot, reshape, and summarize data.
  • Handle time series smoothly.
  • Catch common errors with big data.

With these skills, you can now approach much larger datasets on your own laptop!

Thanks for following along!

If you found this lesson helpful, please like, subscribe, and leave your pandas optimization tips or questions below.

Happy analyzing!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.