Mathew K Analytics

Lesson 6 · Mastering Pandas

Introduction to Pandas DataFrame: Essential Operations and Attributes Explained

Welcome! In this lesson, you will learn essential pandas DataFrame skills. You will explore, clean, and analyze real data. By the end, you will be confident…

⬇ Download notebookOpen in Colab ↗

📓 Full notebook

Download .ipynb

Mastering Pandas: DataFrame Basics and Operations#

Welcome! In this lesson, you will learn essential pandas DataFrame skills.

You will explore, clean, and analyze real data. By the end, you will be confident using pandas for projects.

Let us begin!

# Suppress warnings for a cleaner notebook
import warnings
import numpy as np
np.random.seed(42)
warnings.filterwarnings("ignore")

Data Setup (Titanic Dataset)#

You will work with the Titanic passenger dataset.

Let us load and preview the data!

# 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  
# Learn about the DataFrame's basic attributes
print("Columns:", df.columns.tolist())
print("Indexes:", df.index)
print("Data types:\n", df.dtypes)
Columns: ['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp', 'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked']
Indexes: RangeIndex(start=0, stop=891, step=1)
Data types:
 PassengerId      int64
Survived         int64
Pclass           int64
Name            object
Sex             object
Age            float64
SibSp            int64
Parch            int64
Ticket          object
Fare           float64
Cabin           object
Embarked        object
dtype: object
# Take a quick statistical look at numeric columns
print(df.describe())
       PassengerId    Survived      Pclass         Age       SibSp  \
count   891.000000  891.000000  891.000000  714.000000  891.000000   
mean    446.000000    0.383838    2.308642   29.699118    0.523008   
std     257.353842    0.486592    0.836071   14.526497    1.102743   
min       1.000000    0.000000    1.000000    0.420000    0.000000   
25%     223.500000    0.000000    2.000000   20.125000    0.000000   
50%     446.000000    0.000000    3.000000   28.000000    0.000000   
75%     668.500000    1.000000    3.000000   38.000000    1.000000   
max     891.000000    1.000000    3.000000   80.000000    8.000000   

            Parch        Fare  
count  891.000000  891.000000  
mean     0.381594   32.204208  
std      0.806057   49.693429  
min      0.000000    0.000000  
25%      0.000000    7.910400  
50%      0.000000   14.454200  
75%      0.000000   31.000000  
max      6.000000  512.329200  

Basic Data Selection: Columns and Rows#

You can select columns and rows in several friendly ways.

Let us try selecting specific data!

# Select a single column as a Series
ages = df['Age']
print(ages.head())
0    22.0
1    38.0
2    26.0
3    35.0
4    35.0
Name: Age, dtype: float64
# Select multiple columns as a new DataFrame
df_small = df[['Survived', 'Sex', 'Age']]
print(df_small.head())
   Survived     Sex   Age
0         0    male  22.0
1         1  female  38.0
2         1  female  26.0
3         1  female  35.0
4         0    male  35.0
# Select rows by index values using loc
print(df.loc[0:4, ['Name', 'Pclass', 'Survived']])
                                                Name  Pclass  Survived
0                            Braund, Mr. Owen Harris       3         0
1  Cumings, Mrs. John Bradley (Florence Briggs Th...       1         1
2                             Heikkinen, Miss. Laina       3         1
3       Futrelle, Mrs. Jacques Heath (Lily May Peel)       1         1
4                           Allen, Mr. William Henry       3         0
# Select by row number position with iloc
print(df.iloc[0:5, 0:4])
   PassengerId  Survived  Pclass  \
0            1         0       3   
1            2         1       1   
2            3         1       3   
3            4         1       1   
4            5         0       3   

                                                Name  
0                            Braund, Mr. Owen Harris  
1  Cumings, Mrs. John Bradley (Florence Briggs Th...  
2                             Heikkinen, Miss. Laina  
3       Futrelle, Mrs. Jacques Heath (Lily May Peel)  
4                           Allen, Mr. William Henry  

Data Cleaning: Handling Missing Values#

Real data is messy! Pandas makes it easier to handle missing values.

You will quickly check for and fill in missing data.

# Check for missing values in each column
print(df.isnull().sum())
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
# Fill missing Age values with the median age
age_median = df['Age'].median()
df['Age'].fillna(age_median, inplace=True)
print(df['Age'].isnull().sum())
0
# Drop rows with missing Embarked values
df = df.dropna(subset=['Embarked'])
print(df.shape)
(889, 12)

Filtering Data: Conditional Selection#

It is often useful to focus on certain passengers based on rules.

Let us practice creating smart filters!

# Only look at female passengers
females = df[df['Sex'] == 'female']
print(females.shape)
print(females.head(2))
(312, 12)
   PassengerId  Survived  Pclass  \
1            2         1       1   
2            3         1       3   

                                                Name     Sex   Age  SibSp  \
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  
1      0          PC 17599  71.2833   C85        C  
2      0  STON/O2. 3101282   7.9250   NaN        S  
# Filter: Passengers who paid more than $100
rich = df[df['Fare'] > 100]
print(rich[['Name', 'Fare']].head())
                                               Name      Fare
27                   Fortune, Mr. Charles Alexander  263.0000
31   Spencer, Mrs. William Augustus (Marie Eugenie)  146.5208
88                       Fortune, Miss. Mabel Helen  263.0000
118                        Baxter, Mr. Quigg Edmond  247.5208
195                            Lurette, Miss. Elise  146.5208
# Multi-condition filter: Male, age < 18, survived
boys = df[(df['Sex'] == 'male') & (df['Age'] < 18) & (df['Survived'] == 1)]
print(boys[['Name', 'Age', 'Survived']])
                                                Name    Age  Survived
78                     Caldwell, Master. Alden Gates   0.83         1
125                     Nicola-Yarred, Master. Elias  12.00         1
165  Goldsmith, Master. Frank John William "Frankie"   9.00         1
183                        Becker, Master. Richard F   1.00         1
193                       Navratil, Master. Michel M   3.00         1
220                   Sunderland, Mr. Victor Francis  16.00         1
261                Asplund, Master. Edvin Rojj Felix   3.00         1
305                   Allison, Master. Hudson Trevor   0.92         1
340                   Navratil, Master. Edmond Roger   2.00         1
348           Coutts, Master. William Loch "William"   3.00         1
407                   Richards, Master. William Rowe   3.00         1
445                        Dodge, Master. Washington   4.00         1
489            Coutts, Master. Eden Leslie "Neville"   9.00         1
549                   Davies, Master. John Morgan Jr   8.00         1
550                      Thayer, Mr. John Borland Jr  17.00         1
751                              Moor, Master. Meier   6.00         1
755                        Hamalainen, Master. Viljo   0.67         1
788                       Dean, Master. Bertram Vere   1.00         1
802              Carter, Master. William Thornton II  11.00         1
803                  Thomas, Master. Assad Alexander   0.42         1
827                            Mallet, Master. Andre   1.00         1
831                  Richards, Master. George Sibley   0.83         1
869                  Johnson, Master. Harold Theodor   4.00         1

GroupBy and Aggregation: Summarize by Groups#

Let us see summary statistics for different passenger groups.

Grouping helps you find patterns.

# Average fare by passenger class
print(df.groupby('Pclass')['Fare'].mean())
Pclass
1    84.193516
2    20.662183
3    13.675550
Name: Fare, dtype: float64
# Group by sex and survival, then count passengers
print(df.groupby(['Sex', 'Survived'])['PassengerId'].count())
Sex     Survived
female  0            81
        1           231
male    0           468
        1           109
Name: PassengerId, dtype: int64
# Aggregating multiple statistics
print(df.groupby('Sex')['Age'].agg(['mean', 'median', 'min', 'max']))
             mean  median   min   max
Sex                                  
female  27.788462    28.0  0.75  63.0
male    30.140676    28.0  0.42  80.0

Merging and Joining: Combine DataFrames#

Suppose you have two tables. Pandas makes joining easy.

Let us join a DataFrame of passenger titles to our Titanic dataset.

# Create a simple lookup table of titles
titles = pd.DataFrame({
    'Name': df['Name'][:4],
    'Title': ['Mr.', 'Mrs.', 'Miss.', 'Master.']
})
print(titles)
                                                Name    Title
0                            Braund, Mr. Owen Harris      Mr.
1  Cumings, Mrs. John Bradley (Florence Briggs Th...     Mrs.
2                             Heikkinen, Miss. Laina    Miss.
3       Futrelle, Mrs. Jacques Heath (Lily May Peel)  Master.
# Do a left join to add the Title information
df_joined = df.merge(titles, on='Name', how='left')
print(df_joined[['Name', 'Title']].head(6))
                                                Name    Title
0                            Braund, Mr. Owen Harris      Mr.
1  Cumings, Mrs. John Bradley (Florence Briggs Th...     Mrs.
2                             Heikkinen, Miss. Laina    Miss.
3       Futrelle, Mrs. Jacques Heath (Lily May Peel)  Master.
4                           Allen, Mr. William Henry      NaN
5                                   Moran, Mr. James      NaN

Reshaping: Pivot Tables#

Pivot tables help you summarize and compare groups in a table format.

Let us see how many survived in each class and by sex.

# Make a pivot table for survival by class and sex
table = pd.pivot_table(df, values='PassengerId',
                       index=['Pclass'],
                       columns=['Sex'],
                       aggfunc='count')
print(table)
Sex     female  male
Pclass              
1           92   122
2           76   108
3          144   347

Visualizing with Pandas: Survival Counts#

A quick bar chart helps you see differences across groups.

Let us visualize survival by passenger class.

# Plot a bar chart: Survival rate by class
import matplotlib.pyplot as plt
df.groupby('Pclass')['Survived'].mean().plot(kind='bar')
plt.ylabel('Survival Rate')
plt.title('Titanic Survival Rate by Passenger Class')
plt.show()
No description has been provided for this image

Mini-Project: Exploratory Data Analysis#

Let us try a short challenge. You will investigate age, fare, and survival.

Practice analyzing and plotting!

# Visualize Fare vs. Age by Survival
plt.figure(figsize=(6,4))
colors = ['red' if s == 0 else 'green' for s in df['Survived']]
plt.scatter(df['Age'], df['Fare'], c=colors, alpha=0.5)
plt.xlabel('Age')
plt.ylabel('Fare')
plt.title('Fare vs Age, Colored by Survival')
plt.show()
No description has been provided for this image

Best Practices and Performance Tips#

Keep code readable: use comments, clear variable names, and meaningful column names.

Use vectorized pandas methods, not loops, for speed.

Always check your data before and after cleaning.

# Example: Avoid for-loops when possible
df['FareSquared'] = df['Fare'] ** 2
print(df[['Fare', 'FareSquared']].head())
      Fare  FareSquared
0   7.2500    52.562500
1  71.2833  5081.308859
2   7.9250    62.805625
3  53.1000  2819.610000
4   8.0500    64.802500

Common Issues and Debugging in Pandas#

Watch for typos in column names pandas will give a KeyError.

If code is slow, check if a loop can be replaced by a vectorized method.

When in doubt, print your DataFrame's shape and head.

# Intentional typo: Try a wrong column name
try:
    print(df['Agge'].head())
except KeyError as e:
    print("Error:", e)
    
Error: 'Agge'
# Practice: Rename column safely to fix typos
df.rename(columns={'FareSquared': 'Fare_Squared'}, inplace=True)
print(df.columns)
Index(['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
       'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked', 'Fare_Squared'],
      dtype='object')

Challenge Yourself!#

Try these:

  1. Find the youngest and oldest passenger in each class.

  2. Create a histogram of fares.

  3. Make a new column flagging passengers as "child" if age < 13.

Pause and try them yourself!

Recap#

You learned to load, explore, clean, join, and visualize data with pandas.

These skills help you work fast and ask deeper questions about real data.

Keep practicing and you will master pandas!

Thank You and Next Steps!#

Thank you for learning with us.

Subscribe for more lessons, and leave your favorite pandas tip in the comments!

Practice, experiment, and you will soon be a pandas pro.

Found this useful?

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