Mathew K Analytics

Lesson 9 · Mastering Pandas

Hands-On With Pandas: Creating and Exploring DataFrames

In this lesson, we dive into pandas basics and intermediate techniques. Explore how to create, manipulate, and analyze tables of data using Python. Pandas…

⬇ 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 With Pandas: Creating and Exploring DataFrames#

In this lesson, we dive into pandas basics and intermediate techniques. Explore how to create, manipulate, and analyze tables of data using Python.

What is pandas?#

Pandas is a Python library for working with tabular data. It helps you load, clean, explore, and analyze large datasets efficiently.

import warnings
warnings.filterwarnings("ignore")

# First, import pandas with the standard nickname.
import pandas as pd
import numpy as np
np.random.seed(42)

Creating Your First DataFrame#

A DataFrame is like a table in Excel: rows and columns with labels. Let's build a simple DataFrame from scratch.

data = {
    "Name": ["Alice", "Bob", "Charlie"],
    "Age": [25, 32, 28],
    "City": ["London", "Paris", "Berlin"]
}
df_small = pd.DataFrame(data)
print(df_small)
      Name  Age    City
0    Alice   25  London
1      Bob   32   Paris
2  Charlie   28  Berlin

Loading Real-World Data: The Titanic Dataset#

We often need to load data from an online data file. The Titanic dataset is a classic example for data analysis.

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  
# Let us see what columns exist and the types of data inside.
print(df.columns)
print(df.dtypes)
Index(['PassengerId', 'Survived', 'Pclass', 'Name', 'Sex', 'Age', 'SibSp',
       'Parch', 'Ticket', 'Fare', 'Cabin', 'Embarked'],
      dtype='object')
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
# Peek at the last five rows to see other samples.
print(df.tail())
     PassengerId  Survived  Pclass                                      Name  \
886          887         0       2                     Montvila, Rev. Juozas   
887          888         1       1              Graham, Miss. Margaret Edith   
888          889         0       3  Johnston, Miss. Catherine Helen "Carrie"   
889          890         1       1                     Behr, Mr. Karl Howell   
890          891         0       3                       Dooley, Mr. Patrick   

        Sex   Age  SibSp  Parch      Ticket   Fare Cabin Embarked  
886    male  27.0      0      0      211536  13.00   NaN        S  
887  female  19.0      0      0      112053  30.00   B42        S  
888  female   NaN      1      2  W./C. 6607  23.45   NaN        S  
889    male  26.0      0      0      111369  30.00  C148        C  
890    male  32.0      0      0      370376   7.75   NaN        Q  

Data Cleaning: Handling Missing Data#

Real-world data is often messy. We must identify and handle missing values before analysis.

# 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
# Drop rows where the "Age" column is missing.
df_clean = df.dropna(subset=["Age"])
print(f"Rows before: {df.shape[0]}, after: {df_clean.shape[0]}")
Rows before: 891, after: 714
# Fill missing "Embarked" values with the most common port.
most_common_port = df["Embarked"].mode()[0]
df_filled = df.fillna({"Embarked": most_common_port})
print(df_filled["Embarked"].isnull().sum())
0

Selecting Data: Rows and Columns#

You often want just a part of the table. pandas makes it easy to access columns or rows with simple labels or positions.

# Get all the names of passengers.
names = df["Name"]
print(names.head(5))
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
Name: Name, dtype: object
# Select rows where passengers are female and under 18.
young_females = df[(df["Sex"] == "female") & (df["Age"] < 18)]
print(young_females[["Name", "Age", "Sex"]].head())
                                    Name   Age     Sex
9    Nasser, Mrs. Nicholas (Adele Achem)  14.0  female
10       Sandstrom, Miss. Marguerite Rut   4.0  female
14  Vestrom, Miss. Hulda Amanda Adolfina  14.0  female
22           McGowan, Miss. Anna "Annie"  15.0  female
24         Palsson, Miss. Torborg Danira   8.0  female

Sorting and Descriptive Statistics#

Sorting data and getting summary stats help us spot patterns quickly.

# Sort by Age from youngest to oldest.
sorted_by_age = df.sort_values("Age")
print(sorted_by_age[["Name", "Age"]].head(5))
                                Name   Age
803  Thomas, Master. Assad Alexander  0.42
755        Hamalainen, Master. Viljo  0.67
644           Baclini, Miss. Eugenie  0.75
469    Baclini, Miss. Helene Barbara  0.75
78     Caldwell, Master. Alden Gates  0.83
# Show summary statistics for 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  
# How many unique ticket classes and what are they?
print(df["Pclass"].unique())
print(df["Pclass"].value_counts())
[3 1 2]
Pclass
3    491
1    216
2    184
Name: count, dtype: int64

Grouping and Aggregating Data#

Grouping helps you see big patterns, like survival rates for different groups.

# What percent of men and women survived?
grouped = df.groupby("Sex")["Survived"].mean()
print((grouped * 100).round(2))
Sex
female    74.20
male      18.89
Name: Survived, dtype: float64
# What is the average age for each ticket class?
avg_age_per_class = df.groupby("Pclass")["Age"].mean()
print(avg_age_per_class.round(1))
Pclass
1    38.2
2    29.9
3    25.1
Name: Age, dtype: float64

Combining Columns: Creating New Features#

Sometimes, you need to make new columns by combining or transforming others.

# Create a "FamilySize" column (siblings/spouses + parents/children + self).
df["FamilySize"] = df["SibSp"] + df["Parch"] + 1
print(df[["Name", "FamilySize"]].head(5))
                                                Name  FamilySize
0                            Braund, Mr. Owen Harris           2
1  Cumings, Mrs. John Bradley (Florence Briggs Th...           2
2                             Heikkinen, Miss. Laina           1
3       Futrelle, Mrs. Jacques Heath (Lily May Peel)           2
4                           Allen, Mr. William Henry           1

Merging DataFrames: Join Two Tables#

Use merging for cases like joining passengers with extra info from another file or dataset.

# Make a toy table with titles by name.
titles = pd.DataFrame({
    "Name": ["Alice", "Bob", "Charlie"],
    "Title": ["Ms", "Mr", "Dr"]
})
merged = pd.merge(df_small, titles, on="Name", how="left")
print(merged)
      Name  Age    City Title
0    Alice   25  London    Ms
1      Bob   32   Paris    Mr
2  Charlie   28  Berlin    Dr

Pivot Tables: Quick Summaries by Group#

Pivot tables quickly summarize data with one line per group.

pivot = pd.pivot_table(df, index="Pclass", columns="Sex", values="Survived", aggfunc="mean")
print(pivot.round(2))
Sex     female  male
Pclass              
1         0.97  0.37
2         0.92  0.16
3         0.50  0.14

The Titanic dataset does not have real dates, so let us try the Flights dataset for this.

import seaborn as sns
df_flight = sns.load_dataset('flights')
print(df_flight.shape)
print(df_flight.head(3))
(144, 3)
   year month  passengers
0  1949   Jan         112
1  1949   Feb         118
2  1949   Mar         132
# Convert year and month to a datetime and plot passenger trends.
df_flight["Date"] = pd.to_datetime(df_flight["year"].astype(str) + "-" + df_flight["month"].astype(str) + "-01")
df_flight = df_flight.sort_values("Date")
df_flight.set_index("Date")["passengers"].plot(title="Monthly Flight Passengers")
<Axes: title={'center': 'Monthly Flight Passengers'}, xlabel='Date'>
No description has been provided for this image

Pandas Visualization: Quick Charts#

You can plot right from pandas to quickly explore patterns.

df["Age"].plot(kind="hist", bins=30, title="Age Distribution")
<Axes: title={'center': 'Age Distribution'}, ylabel='Frequency'>
No description has been provided for this image

Mini-Project: Titanic Passenger Analysis#

Let us use all the skills so far on the Titanic data for a quick analysis.

# Input: Which ticket class do you want to explore?
class_choice = input("Enter a ticket class (1, 2, 3): ")
subset = df[df['Pclass'] == int(class_choice)]
print(f"Number of passengers in class {class_choice}: {subset.shape[0]}")
Number of passengers in class 2: 184
# What percent of passengers survived in your chosen class?
survival_rate = subset['Survived'].mean() * 100
print(f"Survival rate: {survival_rate:.1f}%")
Survival rate: 47.3%
# List top 3 youngest survivors in your ticket class.
youngest = subset[subset['Survived'] == 1].sort_values('Age').head(3)
print(youngest[['Name', 'Age']])
                                Name   Age
755        Hamalainen, Master. Viljo  0.67
831  Richards, Master. George Sibley  0.83
78     Caldwell, Master. Alden Gates  0.83

Best Practices and Performance Tips#

  • Use .copy() to avoid changing the original data by accident.
  • Avoid loops: most manipulations are faster with built-in pandas methods.
  • For very big data, use .read_csv() with options like chunksize and dtype.
  • Profile your code with %timeit or %%time to check for slow spots.

Troubleshooting: Common pandas Errors#

  • KeyError: Misspelled or missing column. Check spelling and existance.
  • SettingWithCopyWarning: You probably edited a slice of the DataFrame. Try using .copy().
  • DtypeWarning: Data format is not consistent. Specify data types with dtype when loading.

Challenge: Can You...#

  1. Find the oldest passenger in each ticket class?
  2. Plot a bar chart of survived vs. not survived for each class?
  3. Merge a new table of your own with extra info per person? Pause the video and try one or more!

Recap: What Did You Learn?#

  • Creating and loading DataFrames
  • Cleaning, selecting, grouping, joining and visualizing data
  • Running analyses on real datasets
  • Building confidence for your own Python data projects!

Thanks for learning pandas! If you enjoyed this lesson, please like and subscribe for more practical data science videos. Happy coding!

Found this useful?

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