5.2. Week 2: Pandas, Data Cleaning, and Introductory EDA#

Welcome! This notebook introduces pandas, one of the most widely used Python libraries for working with data. Whether you’re a biology major analyzing lab results, a business student exploring sales data, or a CS student building a data pipeline — pandas will become one of your most-used tools.

By the end of this notebook, you will be able to:

  • Understand what pandas is and why it matters

  • Create and work with Series and DataFrames

  • Understand how pandas relates to NumPy arrays

  • Use essential pandas functions to explore and clean data


💡 No prior pandas experience required. Basic familiarity with Python (variables, lists, dictionaries) will be helpful. September 21 · Bo and Kabilan

Read the worked examples in order. This week covers pandas, cleaning and manipulating tables, and introductory EDA. Plotting and feature engineering follow in Week 3.

5.2.1. What is Pandas?#

Pandas (originally short for Panel Data, though everyone just thinks of the animal 🐼) is a Python library built for data manipulation and analysis. It gives you powerful, flexible data structures that make working with structured data — think spreadsheets, CSV files, or database tables — fast and intuitive.

Why is pandas so popular?

  • It handles messy, real-world data gracefully: missing values, mixed types, inconsistent formatting

  • It reads from many file formats: CSV, Excel, JSON, SQL databases, and more

  • It has rich tools for filtering, grouping, reshaping, and summarizing data

  • It integrates with the broader Python data science ecosystem: NumPy, Matplotlib, scikit-learn, etc.

Pandas is built on top of NumPy, which we’ll touch on later. For now, think of pandas as adding a friendlier, more expressive layer on top of NumPy’s raw numerical power.

Installing pandas: If working locally, run pip install pandas. In Google Colab or most Jupyter environments, it comes pre-installed.

# The standard way to import pandas is with the alias 'pd'
# This convention is followed universally — you'll see it in virtually every tutorial
import pandas as pd
import numpy as np  # We'll also use numpy throughout this notebook

5.2.2. Series#

A Series is the simplest pandas data structure. Think of it as a single column of data — like one column in a spreadsheet.

More precisely, a Series is a one-dimensional labeled array. It has two parts:

  • Values: the actual data (numbers, strings, booleans, etc.)

  • An index: a label for each value (by default: 0, 1, 2, … but can be anything meaningful)

The index is what makes a Series more powerful than a plain Python list. It lets you access data by label rather than just position — very useful when your data has meaningful identifiers like dates, names, or country codes.

Real-world examples of a Series:

  • Daily high temperatures for a week

  • Ages of patients in a medical study

  • Stock prices over time

  • Responses to a single survey question

# --- Creating a Series from a Python list ---
# By default, the index is 0, 1, 2, ...
temperatures = pd.Series([72, 75, 68, 80, 77, 65, 70])
print("Temperatures Series (default index):")
print(temperatures)
Temperatures Series (default index):
0    72
1    75
2    68
3    80
4    77
5    65
6    70
dtype: int64

pd.Series(data, index=None, dtype=None, name=None)

Creates a one-dimensional labeled array.

Parameter

What it does

data

The values — can be a list, dict, scalar, or NumPy array

index

Custom labels for each element. Defaults to 0, 1, 2, ...

dtype

Force a specific data type (e.g. float, int, str)

name

Gives the Series a name, which shows up as the column label when placed in a DataFrame

Common usage patterns:

# From a list (default integer index)
s = pd.Series([10, 20, 30])

# With a custom string index
s = pd.Series([10, 20, 30], index=["a", "b", "c"])

# From a dict — keys become the index automatically
s = pd.Series({"Mon": 72, "Tue": 75, "Wed": 68})

# Give it a name (useful when converting to DataFrame later)
s = pd.Series([1.0, 2.5, 3.7], name="score")
# --- Creating a Series with a custom index ---
# Now each value is labeled with the day of the week
temperatures = pd.Series(
    [72, 75, 68, 80, 77, 65, 70],
    index=["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
)
print("Temperatures with day labels:")
print(temperatures)
print()

# Access a single value by its label
print("Thursday's temperature:", temperatures["Thu"])
print()

# Slice a range of values (label-based slicing is INCLUSIVE of the end label)
print("Weekday temperatures (Mon through Fri):")
print(temperatures["Mon":"Fri"])
Temperatures with day labels:
Mon    72
Tue    75
Wed    68
Thu    80
Fri    77
Sat    65
Sun    70
dtype: int64

Thursday's temperature: 80

Weekday temperatures (Mon through Fri):
Mon    72
Tue    75
Wed    68
Thu    80
Fri    77
dtype: int64
# --- Creating a Series from a dictionary ---
# The dictionary keys become the index automatically
enrollment = pd.Series({
    "Biology": 320,
    "Computer Science": 540,
    "Economics": 415,
    "History": 210,
    "Psychology": 480
})
print("Department Enrollment:")
print(enrollment)
Department Enrollment:
Biology             320
Computer Science    540
Economics           415
History             210
Psychology          480
dtype: int64
# --- Useful Series attributes and methods ---

print("Data type of values:", enrollment.dtype)
print("Number of elements: ", len(enrollment))
print("Index:              ", enrollment.index.tolist())
print()

# Basic statistics — pandas computes these instantly
print("Mean enrollment:", enrollment.mean())
print("Max enrollment: ", enrollment.max())
print("Largest dept:   ", enrollment.idxmax())  # idxmax returns the INDEX LABEL, not the value
print()

# .describe() gives a full statistical summary
print(enrollment.describe())
Data type of values: int64
Number of elements:  5
Index:               ['Biology', 'Computer Science', 'Economics', 'History', 'Psychology']

Mean enrollment: 393.0
Max enrollment:  540
Largest dept:    Computer Science

count      5.000000
mean     393.000000
std      130.843418
min      210.000000
25%      320.000000
50%      415.000000
75%      480.000000
max      540.000000
dtype: float64

Key Series Attributes & Methods

Attribute / Method

What it returns

s.dtype

The data type of the values (e.g. int64, float64, object)

s.index

The Index object holding all labels

s.values

The underlying NumPy array of values

len(s)

Number of elements

s.shape

Tuple (n,) where n is the length

s.mean() / s.sum() / s.std()

Aggregate statistics

s.min() / s.max()

Minimum and maximum values

s.idxmin() / s.idxmax()

Index label of the min / max value

s.describe()

Full statistical summary (count, mean, std, quartiles)

s.value_counts()

Frequency of each unique value

s.unique()

Array of distinct values

s.isnull() / s.notnull()

Boolean mask for missing / present values

Example:

scores = pd.Series([88, 95, 72, 95, 88, 100], index=["Alex","Andre","Anirra","Aniruthan","Bo","Christopher"])

print(scores.mean())        # 89.67
print(scores.idxmax())      # Christopher
print(scores.value_counts())
# 88     2
# 95     2
# 72     1
# 100    1
# --- Filtering a Series with boolean conditions ---
# You can use comparisons to filter values, just like in a spreadsheet

large_depts = enrollment[enrollment > 400]
print("Departments with more than 400 students:")
print(large_depts)
print()

# Arithmetic works element-wise — no loop needed!
# What if enrollment grows 10% next year?
projected = enrollment * 1.10
print("Projected enrollment with 10% growth:")
print(projected.round(0).astype(int))
Departments with more than 400 students:
Computer Science    540
Economics           415
Psychology          480
dtype: int64

Projected enrollment with 10% growth:
Biology             352
Computer Science    594
Economics           457
History             231
Psychology          528
dtype: int64

Boolean Filtering & Arithmetic on Series

You can apply comparisons (>, <, ==, !=, >=, <=) to a Series to get a Boolean mask, then use that mask to filter values. This is much more readable than a loop.

Filtering examples:

s = pd.Series([10, 20, 30, 40, 50], index=["a","b","c","d","e"])

# Boolean mask
print(s > 25)         # False, False, True, True, True

# Filter using the mask
print(s[s > 25])      # c 30, d 40, e 50

# Combine conditions
print(s[(s > 15) & (s < 45)])   # b 20, c 30, d 40

Arithmetic (vectorized — no loops needed):

print(s * 2)          # All values doubled
print(s + 100)        # 100 added to each value
print(np.sqrt(s))     # Square root of each value (uses NumPy)

5.2.3. DataFrames#

If a Series is a single column, a DataFrame is an entire table — rows and columns, like a spreadsheet or a database table. It is the most important pandas data structure, and the one you’ll use most.

A DataFrame is a two-dimensional labeled data structure where:

  • Each column is a Series (and can have a different data type)

  • Each row has an index label

  • Columns also have names

You can think of a DataFrame as a dictionary where each key is a column name and each value is a Series — all sharing the same row index.

Real-world examples of a DataFrame:

  • A spreadsheet of student grades across multiple assignments

  • A table of patient records: age, weight, blood type, diagnosis

  • A dataset of countries with population, GDP, and life expectancy

  • Any CSV file you’d open in Excel

pd.DataFrame(data, index=None, columns=None)

Creates a two-dimensional table. The most common ways to build one:

Source

Example

Dict of lists

pd.DataFrame({"a": [1,2], "b": [3,4]})

List of dicts

pd.DataFrame([{"a":1,"b":3}, {"a":2,"b":4}])

NumPy 2D array

pd.DataFrame(arr, columns=["x","y","z"])

Another DataFrame

Selects/renames existing columns

Key attributes:

Attribute

Description

df.shape

(rows, cols) tuple

df.columns

Column names (Index object)

df.index

Row labels

df.dtypes

Data type of each column

df.head(n)

First n rows (default 5)

df.tail(n)

Last n rows (default 5)

# --- Creating a DataFrame from a dictionary ---
# Each key is a column name; each list is the column's values
# All lists must be the same length!

students = pd.DataFrame({
    "name":    ["Alex", "Andre", "Anirra", "Aniruthan", "Bo", "Christopher"],
    "major":   ["Biology", "CS", "Economics", "Biology", "CS", "History"],
    "year":    [2, 3, 1, 4, 2, 3],
    "gpa":     [3.8, 3.5, 3.9, 2.7, 3.6, 3.2],
    "credits": [60, 90, 30, 120, 60, 90]
})

print(students)
          name      major  year  gpa  credits
0         Alex    Biology     2  3.8       60
1        Andre         CS     3  3.5       90
2       Anirra  Economics     1  3.9       30
3    Aniruthan    Biology     4  2.7      120
4           Bo         CS     2  3.6       60
5  Christopher    History     3  3.2       90
# --- Selecting columns ---

# Single column — returns a Series
print("GPA column (this is a Series):")
print(students["gpa"])
print()

# Multiple columns in a list — returns a DataFrame
print("Name and Major (this is a DataFrame):")
print(students[["name", "major"]])
GPA column (this is a Series):
0    3.8
1    3.5
2    3.9
3    2.7
4    3.6
5    3.2
Name: gpa, dtype: float64

Name and Major (this is a DataFrame):
          name      major
0         Alex    Biology
1        Andre         CS
2       Anirra  Economics
3    Aniruthan    Biology
4           Bo         CS
5  Christopher    History

Selecting Columns

# Single column → returns a Series
df["name"]

# Multiple columns → returns a DataFrame
df[["name", "gpa"]]

# Dot notation (only works when column name has no spaces or special characters)
df.name

⚠️ Always prefer df["col"] over df.col — dot notation silently fails if the column name collides with a DataFrame method (e.g. a column named "count" or "sum").

Example:

# Get just the names of students with GPA above 3.5
top_students = students[students["gpa"] > 3.5]["name"]
print(top_students)
# 0        Alex
# 2      Anirra
# 4          Bo
# --- Selecting rows and cells with .loc and .iloc ---

# .loc uses INDEX LABELS (with default integer index, label == position)
print("Row with index label 2 (Anirra):")
print(students.loc[2])
print()

# Select a range of rows AND specific columns
# .loc slicing is INCLUSIVE on both ends
print("Rows 0-2, name and gpa columns:")
print(students.loc[0:2, ["name", "gpa"]])
print()

# .iloc uses INTEGER POSITIONS (like list indexing — exclusive end)
print("Rows at positions 0-2 (iloc — exclusive end):")
print(students.iloc[0:3, 0:3])  # rows 0,1,2 and columns 0,1,2
Row with index label 2 (Anirra):
name          Anirra
major      Economics
year               1
gpa              3.9
credits           30
Name: 2, dtype: object

Rows 0-2, name and gpa columns:
     name  gpa
0    Alex  3.8
1   Andre  3.5
2  Anirra  3.9

Rows at positions 0-2 (iloc — exclusive end):
     name      major  year
0    Alex    Biology     2
1   Andre         CS     3
2  Anirra  Economics     1

.loc vs .iloc — Label vs Position

This distinction trips up nearly every pandas beginner. Here’s the rule:

Accessor

Selects by

End of slice

.loc[row, col]

Label (index value or column name)

Inclusive

.iloc[row, col]

Integer position (0-based, like a list)

Exclusive

.loc examples:

df.loc[3]                        # Row whose index label is 3
df.loc[1:3, "name":"gpa"]        # Rows 1–3 (inclusive), columns name through gpa (inclusive)
df.loc[df["gpa"] > 3.5, "name"] # Filter rows + select one column
df.loc[:, ["name", "major"]]     # All rows, two specific columns

.iloc examples:

df.iloc[0]           # First row by position
df.iloc[-1]          # Last row by position
df.iloc[0:3, 0:2]    # Rows 0–2, columns 0–1 (exclusive end)
df.iloc[:, 1]        # All rows, second column

Setting values with .loc:

# Change a specific cell
df.loc[2, "gpa"] = 4.0

# Set an entire column for filtered rows
df.loc[df["year"] == 1, "honor_roll"] = False
# --- Filtering rows with boolean conditions ---
# Pass a True/False condition — only rows where True is kept

high_gpa = students[students["gpa"] > 3.5]
print("Students with GPA > 3.5:")
print(high_gpa)
print()

# Combine conditions with & (and) or | (or)
# Parentheses around each condition are REQUIRED
cs_sophomores = students[(students["major"] == "CS") & (students["year"] == 2)]
print("CS students in year 2:")
print(cs_sophomores)
Students with GPA > 3.5:
     name      major  year  gpa  credits
0    Alex    Biology     2  3.8       60
2  Anirra  Economics     1  3.9       30
4      Bo         CS     2  3.6       60

CS students in year 2:
  name major  year  gpa  credits
4   Bo    CS     2  3.6       60
# --- Adding new columns ---

# A simple calculation: credits remaining before graduation (120 total)
students["credits_remaining"] = 120 - students["credits"]

# A conditional column: are they on the honor roll? (GPA >= 3.7)
# np.where(condition, value_if_true, value_if_false)
students["honor_roll"] = np.where(students["gpa"] >= 3.7, True, False)

print(students)
          name      major  year  gpa  credits  credits_remaining  honor_roll
0         Alex    Biology     2  3.8       60                 60        True
1        Andre         CS     3  3.5       90                 30       False
2       Anirra  Economics     1  3.9       30                 90        True
3    Aniruthan    Biology     4  2.7      120                  0       False
4           Bo         CS     2  3.6       60                 60       False
5  Christopher    History     3  3.2       90                 30       False
# --- Groupby: split, apply, combine ---
# One of the most powerful pandas features.
# groupby splits data into groups, applies a function, then combines the results.

# Average GPA per major
avg_gpa = students.groupby("major")["gpa"].mean().round(2)
print("Average GPA by Major:")
print(avg_gpa)
print()

# Multiple aggregations at once using .agg()
summary = students.groupby("major").agg(
    num_students=("name", "count"),
    avg_gpa=("gpa", "mean"),
    avg_credits=("credits", "mean")
).round(2)
print("Full summary by major:")
print(summary)
Average GPA by Major:
major
Biology      3.25
CS           3.55
Economics    3.90
History      3.20
Name: gpa, dtype: float64

Full summary by major:
           num_students  avg_gpa  avg_credits
major                                        
Biology               2     3.25         90.0
CS                    2     3.55         75.0
Economics             1     3.90         30.0
History               1     3.20         90.0

df.groupby(by) — Split → Apply → Combine

groupby is one of the most powerful patterns in pandas. It:

  1. Splits the DataFrame into groups based on a column’s values

  2. Applies an aggregation function to each group

  3. Combines the results into a new DataFrame

Common aggregation functions:

Function

What it computes

.mean()

Average

.sum()

Total

.count()

Non-null count

.min() / .max()

Smallest / largest

.std()

Standard deviation

.median()

Median value

.agg({"col": "func"})

Different functions per column

Examples:

# Count students per major
students.groupby("major")["name"].count()

# Multiple stats at once with .agg()
students.groupby("major").agg(
    total=("name", "count"),
    avg_gpa=("gpa", "mean"),
    max_gpa=("gpa", "max")
)

# Group by multiple columns
students.groupby(["major", "year"])["gpa"].mean()

# Filter groups with .filter() — keep groups where avg GPA > 3.5
students.groupby("major").filter(lambda g: g["gpa"].mean() > 3.5)

5.2.4. NumPy Arrays#

Before diving into cleaning, it’s worth understanding pandas’ relationship with NumPy.

NumPy (Numerical Python) is the foundational library for numerical computing in Python. Its core object is the ndarray (n-dimensional array) — a fast, efficient grid of values, all of the same data type.

Pandas is built on top of NumPy. Under the hood, every Series and DataFrame column stores its data as a NumPy array. This means:

  • Pandas inherits NumPy’s speed for numerical operations

  • You can easily convert between pandas and NumPy objects

  • Many NumPy functions work directly on pandas objects

When to use NumPy vs. pandas:

Use NumPy when…

Use Pandas when…

Pure numerical data (matrices, vectors)

Data has mixed types (strings + numbers)

Linear algebra, matrix math

Data has meaningful row/column labels

Writing scientific simulations

Reading/writing CSV, Excel, JSON

Maximum raw performance

Groupby, merge, pivot, time-series operations

In practice, you’ll use both together constantly.

# --- Creating NumPy arrays ---

arr = np.array([10, 20, 30, 40, 50])
print("1D NumPy array:     ", arr)
print("Type:               ", type(arr))
print("Element data type:  ", arr.dtype)
print("Shape:              ", arr.shape)  # (5,) = 5 elements, 1 dimension
1D NumPy array:      [10 20 30 40 50]
Type:                <class 'numpy.ndarray'>
Element data type:   int64
Shape:               (5,)
# --- 2D NumPy array (a matrix) ---
matrix = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
])
print("2D array (matrix):")
print(matrix)
print("Shape:", matrix.shape)   # (3, 3) = 3 rows, 3 columns
print()

# Element-wise operations — no loops needed!
print("Matrix * 2:")
print(matrix * 2)
print()

# axis=0 means "collapse across rows" → gives per-column result
# axis=1 means "collapse across columns" → gives per-row result
print("Column means (axis=0):", matrix.mean(axis=0))
print("Row means    (axis=1):", matrix.mean(axis=1))
2D array (matrix):
[[1 2 3]
 [4 5 6]
 [7 8 9]]
Shape: (3, 3)

Matrix * 2:
[[ 2  4  6]
 [ 8 10 12]
 [14 16 18]]

Column means (axis=0): [4. 5. 6.]
Row means    (axis=1): [2. 5. 8.]
# --- Converting between NumPy and Pandas ---

# NumPy array → pandas Series
gpa_array = np.array([3.8, 3.7, 3.9, 3.0, 3.6, 3.2])
gpa_series = pd.Series(gpa_array, name="gpa")
print("Series from NumPy array:")
print(gpa_series)
print()

# pandas Series → NumPy array
back_to_np = gpa_series.to_numpy()
print("Back to NumPy:", back_to_np, "Type:", type(back_to_np))
print()

# DataFrame → NumPy array (loses all labels!)
numeric_df = students[["year", "gpa", "credits"]].to_numpy()
print("Numeric DataFrame as NumPy array:")
print(numeric_df)
Series from NumPy array:
0    3.8
1    3.7
2    3.9
3    3.0
4    3.6
5    3.2
Name: gpa, dtype: float64

Back to NumPy: [3.8 3.7 3.9 3.  3.6 3.2] Type: <class 'numpy.ndarray'>

Numeric DataFrame as NumPy array:
[[  2.    3.8  60. ]
 [  3.    3.5  90. ]
 [  1.    3.9  30. ]
 [  4.    2.7 120. ]
 [  2.    3.6  60. ]
 [  3.    3.2  90. ]]
# --- np.nan: the standard missing value ---
# np.nan (Not a Number) is used throughout NumPy and pandas to represent
# missing or undefined numerical values

vals = np.array([1.0, 2.0, np.nan, 4.0, np.nan, 6.0])
print("Array with NaN:", vals)
print("Naive sum (propagates NaN!):  ", vals.sum())
print("NaN-safe sum (np.nansum):     ", np.nansum(vals))
print("NaN-safe mean (np.nanmean):   ", np.nanmean(vals))
print()
print("Pandas handles NaN gracefully by default:")
print("pd.Series.sum():", pd.Series(vals).sum())  # pandas skips NaN automatically
Array with NaN: [ 1.  2. nan  4. nan  6.]
Naive sum (propagates NaN!):   nan
NaN-safe sum (np.nansum):      13.0
NaN-safe mean (np.nanmean):    3.25

Pandas handles NaN gracefully by default:
pd.Series.sum(): 13.0

5.2.5. Pandas Cleaning Functions#

In the real world, data is almost never clean when you first receive it. Column names are inconsistent, values are missing, data types are wrong, and rows may be duplicated. Data cleaning is the process of identifying and fixing these problems before you analyze anything.

Experienced analysts often say that 80% of data work is cleaning — and pandas provides an excellent toolkit for it.

We’ll walk through the most essential functions using a realistic, intentionally messy dataset:

  1. Exploring data — head(), tail(), shape, columns, index, info(), describe()

  2. Selecting data — loc, iloc, column selection, boolean filters

  3. Handling missing data — isnull(), dropna(), fillna()

  4. Modifying data — renaming columns, fixing types, standardizing strings

  5. Sorting and deduplication — sort_values(), drop_duplicates()

# Let's create a realistic messy dataset — survey data collected from students.
# Notice the problems intentionally baked in:
#   - Student 102 (Iana) appears twice (duplicate)
#   - Column name '  Name  ' has extra spaces
#   - 'MAJOR' column has inconsistent capitalization: "ds", "DS", "CS", "economics", "Biology"
#   - 'year' column has "third" (a string) instead of 3
#   - Several missing values across multiple columns
#   - 'Extra Column' is entirely empty — useless

raw_data = {
    "Student ID":    [101, 102, 103, 104, 105, 106, 107, 108, 109, 102],
    "  Name  ":      ["Gina", "Iana", "Kabilan", "Nathan", "Earn", None, "Sameer", "Sarah", "Wayland", "Iana"],
    "MAJOR":         ["Math", "ds", "Math", "DS", "Business", "ds", "economics", "CS", "DS", "Biology"],
    "GPA":           [3.8, 3.7, 3.9, 3.0, 3.6, 3.2, None, 3.1, 3.7, 3.5],
    "Year":          [2, 3, 1, 4, 2, 3, 1, "third", 4, 3],
    "scholarship":   ["yes", "no", "yes", "no", "yes", "no", "yes", "no", None, "no"],
    "Extra Column":  [None] * 10
}

df = pd.DataFrame(raw_data)
print(df)
   Student ID   Name        MAJOR  GPA   Year scholarship Extra Column
0         101     Gina       Math  3.8      2         yes         None
1         102     Iana         ds  3.7      3          no         None
2         103  Kabilan       Math  3.9      1         yes         None
3         104   Nathan         DS  3.0      4          no         None
4         105     Earn   Business  3.6      2         yes         None
5         106      NaN         ds  3.2      3          no         None
6         107   Sameer  economics  NaN      1         yes         None
7         108    Sarah         CS  3.1  third          no         None
8         109  Wayland         DS  3.7      4         NaN         None
9         102     Iana    Biology  3.5      3          no         None

5.2.5.1. Step 1: Exploring the Data#

Before fixing anything, you need to understand what you have. These functions help you get oriented in seconds — especially important when your dataset has thousands of rows and you can’t read it all at once.

Exploration Functions in Detail

These are the first functions you should call whenever you load a new dataset.


df.head(n=5) / df.tail(n=5)

  • Returns the first (or last) n rows

  • Default is 5 rows if you don’t pass an argument

  • head() lets you confirm column names, spot obvious problems, and see what the data looks like before touching it

  • tail() is useful for checking if files end with summary rows or footers

df.head(3)    # First 3 rows
df.tail()     # Last 5 rows (default)

df.shape

  • Returns a tuple (number_of_rows, number_of_columns)

  • Not a method — no parentheses needed

  • Useful for checking how many records survived after filtering or dropping

rows, cols = df.shape
print(f"Dataset has {rows} records and {cols} features")

df.columns / df.index

  • df.columns — the column names as an Index object; call .tolist() to get a plain Python list

  • df.index — the row labels (default RangeIndex(0, n))

print(df.columns.tolist())   # ['student_id', 'name', 'major', ...]
print(df.index[:5].tolist()) # [0, 1, 2, 3, 4]
# df.head(n) — show the first n rows (default 5)
# The go-to first command whenever you load a dataset
print("First 5 rows:")
print(df.head())
print()

# df.tail(n) — show the last n rows (default 5)
# Useful for checking if files have trailing summary rows or footers
print("Last 3 rows:")
print(df.tail(3))
First 5 rows:
   Student ID   Name       MAJOR  GPA Year scholarship Extra Column
0         101     Gina      Math  3.8    2         yes         None
1         102     Iana        ds  3.7    3          no         None
2         103  Kabilan      Math  3.9    1         yes         None
3         104   Nathan        DS  3.0    4          no         None
4         105     Earn  Business  3.6    2         yes         None

Last 3 rows:
   Student ID   Name      MAJOR  GPA   Year scholarship Extra Column
7         108    Sarah       CS  3.1  third          no         None
8         109  Wayland       DS  3.7      4         NaN         None
9         102     Iana  Biology  3.5      3          no         None

df.info()

Prints a concise summary of the entire DataFrame:

  • Column names and their data types

  • Number of non-null values per column (how many rows have data)

  • Memory usage

This is the single fastest way to spot: which columns have missing values, which columns are stored as the wrong type (e.g. numbers stored as strings → object dtype), and how big the dataset is.

df.info()
# Output (example):
# RangeIndex: 10 entries, 0 to 9
# Data columns (total 7 columns):
#  #   Column        Non-Null Count  Dtype
# ---  ------        --------------  -----
#  0   Student ID    10 non-null     int64
#  1     Name        9 non-null      object   ← 1 missing
#  2   MAJOR         9 non-null      object   ← 1 missing
#  3   GPA           9 non-null      float64  ← 1 missing
#  4   Year          10 non-null     object   ← stored as object (has "third"!)
#  5   scholarship   9 non-null      object   ← 1 missing
#  6   Extra Column  0 non-null      object   ← completely empty

df.describe(include=None)

Returns summary statistics for numeric columns by default:

Stat

Description

count

Number of non-null values

mean

Arithmetic average

std

Standard deviation

min / max

Smallest / largest value

25% / 50% / 75%

Quartiles

Pass include='all' to also get stats for text columns (unique count, most frequent value, etc.).

df.describe()             # Numeric columns only
df.describe(include='all')  # All columns
df["gpa"].describe()      # Just one column
# df.shape — returns (rows, columns) as a tuple
print("Shape:", df.shape)
print(f"  → {df.shape[0]} rows, {df.shape[1]} columns")
print()

# df.columns — the column names as an Index object
print("Column names:", df.columns.tolist())
print()

# df.index — the row labels (default: 0, 1, 2, ...)
print("Row index:", df.index.tolist())
Shape: (10, 7)
  → 10 rows, 7 columns

Column names: ['Student ID', '  Name  ', 'MAJOR', 'GPA', 'Year', 'scholarship', 'Extra Column']

Row index: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# df.info() — the single most useful orientation command
# Shows: column names, non-null counts, and data types
# A quick scan immediately reveals where your missing values and type issues are

df.info()
<class 'pandas.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 7 columns):
 #   Column        Non-Null Count  Dtype  
---  ------        --------------  -----  
 0   Student ID    10 non-null     int64  
 1     Name        9 non-null      str    
 2   MAJOR         10 non-null     str    
 3   GPA           9 non-null      float64
 4   Year          10 non-null     object 
 5   scholarship   9 non-null      str    
 6   Extra Column  0 non-null      object 
dtypes: float64(1), int64(1), object(2), str(3)
memory usage: 692.0+ bytes
# df.describe() — summary statistics for all numeric columns
# Reports count, mean, std, min, 25th/50th/75th percentile, max
print("Numeric summary:")
print(df.describe())
print()

# include='all' also shows stats for non-numeric columns (like unique count, top value)
print("Full summary (all columns):")
print(df.describe(include='all'))
Numeric summary:
       Student ID       GPA
count   10.000000  9.000000
mean   104.700000  3.500000
std      2.750757  0.324037
min    101.000000  3.000000
25%    102.250000  3.200000
50%    104.500000  3.600000
75%    106.750000  3.700000
max    109.000000  3.900000

Full summary (all columns):
        Student ID   Name   MAJOR       GPA  Year scholarship Extra Column
count    10.000000        9    10  9.000000  10.0           9            0
unique         NaN        8     7       NaN   5.0           2            0
top            NaN     Iana  Math       NaN   3.0          no          NaN
freq           NaN        2     2       NaN   3.0           5          NaN
mean    104.700000      NaN   NaN  3.500000   NaN         NaN          NaN
std       2.750757      NaN   NaN  0.324037   NaN         NaN          NaN
min     101.000000      NaN   NaN  3.000000   NaN         NaN          NaN
25%     102.250000      NaN   NaN  3.200000   NaN         NaN          NaN
50%     104.500000      NaN   NaN  3.600000   NaN         NaN          NaN
75%     106.750000      NaN   NaN  3.700000   NaN         NaN          NaN
max     109.000000      NaN   NaN  3.900000   NaN         NaN          NaN

5.2.5.2. Step 2: Selecting Data with loc and iloc#

You’ll constantly need to slice specific rows, columns, or individual cells from a DataFrame. Pandas gives you two primary tools:

  • .loc[row_label, col_label] — selects by label (the index value or column name). Slicing with .loc is inclusive on both ends.

  • .iloc[row_position, col_position] — selects by integer position (like Python list indexing). Slicing with .iloc is exclusive of the end (standard Python behavior).

A common confusion: with the default integer index, .loc[2] and .iloc[2] look the same. They differ once you change the index — and understanding the distinction will save you from subtle bugs.

# --- .loc examples ---

# Single row by label
print("Row with label 0:")
print(df.loc[0])
print()

# Rows 0-2 (INCLUSIVE) and specific columns
print("Rows 0-2, Name and GPA:")
print(df.loc[0:2, ["  Name  ", "GPA"]])
print()

# Boolean mask — filter rows where GPA > 3.7
print("Rows where GPA > 3.7:")
print(df.loc[df["GPA"] > 3.7])
Row with label 0:
Student ID       101
  Name          Gina
MAJOR           Math
GPA              3.8
Year               2
scholarship      yes
Extra Column    None
Name: 0, dtype: object

Rows 0-2, Name and GPA:
    Name    GPA
0     Gina  3.8
1     Iana  3.7
2  Kabilan  3.9

Rows where GPA > 3.7:
   Student ID   Name   MAJOR  GPA Year scholarship Extra Column
0         101     Gina  Math  3.8    2         yes         None
2         103  Kabilan  Math  3.9    1         yes         None
# --- .iloc examples ---

# First row (position 0)
print("First row by position:")
print(df.iloc[0])
print()

# Rows at positions 1-3 (EXCLUSIVE end), columns at positions 0-2
print("Rows 1-3, first 3 columns:")
print(df.iloc[1:4, 0:3])
print()

# Last row (negative indexing works)
print("Last row:")
print(df.iloc[-1])
First row by position:
Student ID       101
  Name          Gina
MAJOR           Math
GPA              3.8
Year               2
scholarship      yes
Extra Column    None
Name: 0, dtype: object

Rows 1-3, first 3 columns:
   Student ID   Name   MAJOR
1         102     Iana    ds
2         103  Kabilan  Math
3         104   Nathan    DS

Last row:
Student ID          102
  Name             Iana
MAJOR           Biology
GPA                 3.5
Year                  3
scholarship          no
Extra Column       None
Name: 9, dtype: object

5.2.5.3. Step 3: Handling Missing Data#

Missing data is the most common issue you’ll encounter. Pandas represents missing values as NaN (Not a Number) or None.

Your two main options:

  1. Drop the offending rows or columns

  2. Fill the missing values with something meaningful

Which you choose depends on context. Dropping is safer but loses data. Filling preserves data but introduces assumptions — a mean GPA fill is very different from a median fill if your distribution is skewed.

Handling Missing Data in Detail

Pandas uses NaN (Not a Number — from NumPy) and None interchangeably to represent missing values. The key functions are:


df.isnull() / df.notnull()

  • Returns a DataFrame of the same shape filled with True/False

  • isnull() → True where value is missing

  • notnull() → True where value is present

  • Most useful pattern: df.isnull().sum() to count missing values per column

df.isnull()           # Full boolean DataFrame
df.isnull().sum()     # Count NaN per column
df.isnull().sum() / len(df) * 100  # % missing
df[df["gpa"].isnull()]  # Rows where GPA is missing

df.dropna(axis=0, how='any', subset=None, inplace=False)

Parameter

Options

Meaning

axis

0 (rows) or 1 (columns)

What to drop

how

'any' or 'all'

Drop if any NaN vs. all NaN

subset

List of column names

Only check these columns

inplace

True / False

Modify in place vs. return new object

df.dropna()                          # Remove rows with ANY missing value
df.dropna(how='all')                 # Only remove rows that are ENTIRELY empty
df.dropna(subset=["name", "gpa"])    # Remove rows missing name OR gpa
df.dropna(axis=1, how='all')         # Drop columns that are completely empty

df.fillna(value, method=None, inplace=False)

Value type

Example

Typical use case

Scalar

df.fillna(0)

Fill all NaN with zero

Dict

df.fillna({"gpa": 0, "name": "Unknown"})

Different fill per column

method='ffill'

Forward-fill from previous row

Time series

method='bfill'

Back-fill from next row

Time series

.fillna(df["gpa"].mean())

Column mean

Numeric imputation

df["gpa"].fillna(df["gpa"].median())        # Fill with median
df["major"].fillna("Undeclared")            # Fill categorical
df.fillna({"name": "Unknown", "gpa": 3.0})  # Multiple columns at once
# --- Detecting missing values ---

# isnull() returns True where a value is missing
# The most useful pattern: sum per column to count missing values
print("Missing values per column:")
print(df.isnull().sum())
print()

print("Missing % per column:")
print((df.isnull().sum() / len(df) * 100).round(1))
Missing values per column:
Student ID       0
  Name           1
MAJOR            0
GPA              1
Year             0
scholarship      1
Extra Column    10
dtype: int64

Missing % per column:
Student ID        0.0
  Name           10.0
MAJOR             0.0
GPA              10.0
Year              0.0
scholarship      10.0
Extra Column    100.0
dtype: float64
# --- Dropping missing values ---

# dropna() removes any row with at least one NaN (default behavior)
df_no_nulls = df.dropna()
print(f"Original: {df.shape}  →  After dropna(): {df_no_nulls.shape}")
print()

# Drop columns where ALL values are missing (safe — removes truly empty columns)
df_clean_cols = df.dropna(axis=1, how='all')  # axis=1 targets columns
print("Columns remaining after dropping fully-empty columns:")
print(df_clean_cols.columns.tolist())
Original: (10, 7)  →  After dropna(): (0, 7)

Columns remaining after dropping fully-empty columns:
['Student ID', '  Name  ', 'MAJOR', 'GPA', 'Year', 'scholarship']
# --- Filling missing values ---

# Fill numeric NaN with the column's mean
mean_gpa = df["GPA"].mean()
print(f"Mean GPA (excluding NaN): {mean_gpa:.2f}")
df["GPA"] = df["GPA"].fillna(mean_gpa)

# Fill categorical NaN with a default string
df["scholarship"] = df["scholarship"].fillna("unknown")
df["  Name  "]    = df["  Name  "].fillna("Unknown")

print("\nMissing values after filling:")
print(df.isnull().sum())
Mean GPA (excluding NaN): 3.50

Missing values after filling:
Student ID       0
  Name           0
MAJOR            0
GPA              0
Year             0
scholarship      0
Extra Column    10
dtype: int64

5.2.5.4. Step 4: Modifying Data#

Now let’s clean up the structural problems: inconsistent column names, dirty string values, and wrong data types.

Modifying Data in Detail


df.rename(columns={old: new}, index={old: new}, inplace=False)

Renames specific columns or index labels. Uses a dictionary to map old names to new names.

df.rename(columns={"Student ID": "student_id", "GPA": "gpa"})

# Rename multiple columns at once
df.rename(columns={
    "  Name  ": "name",
    "MAJOR": "major",
    "Year": "year"
})

# Rename using a function (e.g. lowercase all column names)
df.rename(columns=str.lower)

Bulk column normalization

A common real-world pattern — fix all column names in one line:

df.columns = df.columns.str.strip().str.lower().str.replace(" ", "_")
# "  Name  " → "name"
# "Student ID" → "student_id"
# "Extra Column" → "extra_column"

df.drop(columns=[], index=[], inplace=False)

Removes columns or rows.

df.drop(columns=["extra_column"])              # Remove one column
df.drop(columns=["col1", "col2"])              # Remove multiple
df.drop(index=[0, 5])                          # Remove rows by label
df.drop(index=df[df["gpa"] < 2.0].index)      # Remove rows matching condition

df["col"].astype(dtype)

Converts a column to a different data type.

df["year"].astype(int)          # String/float → integer
df["gpa"].astype(float)         # Object → float
df["student_id"].astype(str)    # Number → string (for joining/merging)

df["col"].replace({old: new})

Substitutes specific values in a column. Cleaner than a loop.

df["year"].replace("third", 3)
df["major"].replace({"Cs": "CS", "BIOLOGY": "Biology"})

df["col"].map({key: value})

Transforms each value using a dictionary or function. Any value not in the dictionary becomes NaN.

df["scholarship"].map({"yes": True, "no": False})      # Dict mapping
df["name"].map(str.upper)                              # Function mapping
df["major"].map({"CS": "Computer Science", "Bio": "Biology"})
# --- Renaming columns and normalizing column names ---

# Rename individual columns explicitly
df = df.rename(columns={"Student ID": "student_id", "Year": "year"})

# Apply bulk normalization: strip whitespace, lowercase, replace spaces with underscores
# This handles '  Name  ', 'MAJOR', 'Extra Column' all at once
df.columns = df.columns.str.strip().str.lower().str.replace(" ", "_")

print("Cleaned column names:")
print(df.columns.tolist())
Cleaned column names:
['student_id', 'name', 'major', 'gpa', 'year', 'scholarship', 'extra_column']
# --- Dropping a useless column ---
df = df.drop(columns=["extra_column"])
print("Columns after removing 'extra_column':")
print(df.columns.tolist())
Columns after removing 'extra_column':
['student_id', 'name', 'major', 'gpa', 'year', 'scholarship']
# --- Standardizing string values ---
# The 'major' column has 'ds', 'DS', 'Math', 'Business', 'economics', 'CS', 'Biology' — a mess.

print("Before standardizing:")
print(df["major"].value_counts())  # value_counts() shows unique values and how often they appear
print()

# str.title() capitalizes the first letter of each word
df["major"] = df["major"].str.title()

# Edge case: 'Cs' should be 'CS'
df["major"] = df["major"].replace({"Ds": "DS"})

print("After standardizing:")
print(df["major"].value_counts())
Before standardizing:
major
Math         2
ds           2
DS           2
Business     1
economics    1
CS           1
Biology      1
Name: count, dtype: int64

After standardizing:
major
DS           4
Math         2
Business     1
Economics    1
Cs           1
Biology      1
Name: count, dtype: int64
# --- Fixing data types ---
# The 'year' column should be an integer, but has 'third' mixed in

print("Current 'year' column:")
print(df["year"])
print("Data type:", df["year"].dtype)  # 'object' = pandas is storing it as strings
print()

# Step 1: replace the string "third" with the number 3
df["year"] = df["year"].replace("third", 3)

# Step 2: convert the whole column to integer type
df["year"] = df["year"].astype(int)

print("Fixed 'year' column:")
print(df["year"])
print("Data type:", df["year"].dtype)
Current 'year' column:
0        2
1        3
2        1
3        4
4        2
5        3
6        1
7    third
8        4
9        3
Name: year, dtype: object
Data type: object

Fixed 'year' column:
0    2
1    3
2    1
3    4
4    2
5    3
6    1
7    3
8    4
9    3
Name: year, dtype: int64
Data type: int64
# --- Mapping string values to booleans ---
# 'yes'/'no' strings are common in survey data.
# Converting to True/False (boolean) makes filtering easier and saves memory.

df["scholarship"] = df["scholarship"].map({"yes": True, "no": False, "unknown": None})

print("Scholarship column after mapping:")
print(df["scholarship"])
Scholarship column after mapping:
0     True
1    False
2     True
3    False
4     True
5    False
6     True
7    False
8     None
9    False
Name: scholarship, dtype: object

5.2.5.5. Step 5: Sorting and Removing Duplicates#

Sorting and Deduplication in Detail


df.sort_values(by, ascending=True, na_position='last', inplace=False)

Sorts the DataFrame by one or more columns.

Parameter

Description

by

Column name (string) or list of column names

ascending

True (A→Z, low→high) or False (reverse). List for multi-column

na_position

'last' (default) or 'first' — where NaN goes

inplace

Modify in place or return sorted copy

df.sort_values("gpa")                          # Low to high GPA
df.sort_values("gpa", ascending=False)         # High to low GPA
df.sort_values(["major", "gpa"], ascending=[True, False])  # Multi-column
df.sort_values("name", na_position="first")    # Put missing names first

df.duplicated(subset=None, keep='first')

Returns a Boolean Series: True for rows that are duplicates.

keep

Behavior

'first'

Mark all duplicates except the first occurrence

'last'

Mark all duplicates except the last occurrence

False

Mark ALL occurrences of duplicated rows

df.duplicated()                        # Full-row duplicates
df.duplicated(subset="student_id")     # Duplicate based on one column
df[df.duplicated()]                    # Show the duplicate rows
df[df.duplicated(keep=False)]          # Show ALL copies of duplicate rows

df.drop_duplicates(subset=None, keep='first', inplace=False)

Removes duplicate rows (same parameters as duplicated()).

df.drop_duplicates()                             # Remove full-row duplicates
df.drop_duplicates(subset="student_id")          # Keep first occurrence per ID
df.drop_duplicates(subset="student_id", keep="last")  # Keep most recent

df.reset_index(drop=False, inplace=False)

After filtering or dropping rows, the original row numbers create gaps (0, 1, 3, 5, ...). reset_index() rebuilds the index from 0 to n-1.

df = df.reset_index(drop=True)   # drop=True discards the old index instead of adding it as a column
# --- Sorting rows ---

# Sort by a single column, descending
df_by_gpa = df.sort_values("gpa", ascending=False)
print("Sorted by GPA (highest first):")
print(df_by_gpa[["name", "major", "gpa"]])
print()

# Sort by multiple columns: major A-Z, then GPA within each major (high to low)
df_multi = df.sort_values(["major", "gpa"], ascending=[True, False])
print("Sorted by major, then by GPA within major:")
print(df_multi[["name", "major", "gpa"]])
Sorted by GPA (highest first):
      name      major  gpa
2  Kabilan       Math  3.9
0     Gina       Math  3.8
1     Iana         DS  3.7
8  Wayland         DS  3.7
4     Earn   Business  3.6
6   Sameer  Economics  3.5
9     Iana    Biology  3.5
5  Unknown         DS  3.2
7    Sarah         Cs  3.1
3   Nathan         DS  3.0

Sorted by major, then by GPA within major:
      name      major  gpa
9     Iana    Biology  3.5
4     Earn   Business  3.6
7    Sarah         Cs  3.1
1     Iana         DS  3.7
8  Wayland         DS  3.7
5  Unknown         DS  3.2
3   Nathan         DS  3.0
6   Sameer  Economics  3.5
2  Kabilan       Math  3.9
0     Gina       Math  3.8
# --- Finding and removing duplicates ---

# duplicated() returns True for rows that are duplicates of an earlier row
print("Duplicate rows (all columns must match):")
print(df[df.duplicated()])
print()

# More targeted: check if student_id is repeated (it should be unique per student)
print("Rows with duplicate student_id:")
print(df[df.duplicated(subset="student_id")])
print()

# Remove duplicates — keep='first' retains the first occurrence
df = df.drop_duplicates(subset="student_id", keep="first")
print(f"Shape after removing duplicates: {df.shape}")
Duplicate rows (all columns must match):
Empty DataFrame
Columns: [student_id, name, major, gpa, year, scholarship]
Index: []

Rows with duplicate student_id:
   student_id  name    major  gpa  year scholarship
9         102  Iana  Biology  3.5     3       False

Shape after removing duplicates: (9, 6)
# --- Reset the index after dropping rows ---
# After removing rows, your index may have gaps: 0, 1, 3, 5, 6...
# reset_index() rebuilds it as a clean 0-to-n sequence

df = df.reset_index(drop=True)  # drop=True discards the old index rather than adding it as a column

print("Final cleaned DataFrame:")
print(df)
print()
print("Final info:")
df.info()
Final cleaned DataFrame:
   student_id     name      major  gpa  year scholarship
0         101     Gina       Math  3.8     2        True
1         102     Iana         DS  3.7     3       False
2         103  Kabilan       Math  3.9     1        True
3         104   Nathan         DS  3.0     4       False
4         105     Earn   Business  3.6     2        True
5         106  Unknown         DS  3.2     3       False
6         107   Sameer  Economics  3.5     1        True
7         108    Sarah         Cs  3.1     3       False
8         109  Wayland         DS  3.7     4        None

Final info:
<class 'pandas.DataFrame'>
RangeIndex: 9 entries, 0 to 8
Data columns (total 6 columns):
 #   Column       Non-Null Count  Dtype  
---  ------       --------------  -----  
 0   student_id   9 non-null      int64  
 1   name         9 non-null      str    
 2   major        9 non-null      str    
 3   gpa          9 non-null      float64
 4   year         9 non-null      int64  
 5   scholarship  8 non-null      object 
dtypes: float64(1), int64(2), object(1), str(2)
memory usage: 564.0+ bytes

5.2.6. Introductory Exploratory Data Analysis#

Use these questions alongside the inspection, cleaning, and grouped summaries above. EDA starts before cleaning and continues afterward.

5.2.6.1. What is EDA?#

Exploratory Data Analysis (EDA) is essential for understanding our datasets as it reveals underlying trends in our data, transforming it from messy numbers into clear insights. Many people working in data science roles report that this is the process that makes up most of their responsibilities!

EDA is the process of familiarizing ourselves with a new dataset before performing more advanced analysis or modeling. Through iterative EDA, we can better understand our variables, identify problems in the dataset, and discover potential hypotheses.

5.2.6.2. What should we look for during EDA?#

When performing EDA, you can reference a “checklist” of things to consider when examining your data.

Getting to know the data table columns and their types

  • Each column represents a variable in your data, and you should start by identifying what data / storage type the columns are. Data types tell you how each variable is stored in memory, and some data types include integers, floating points, booleans, and strings. You should also determine if columns represent quantitative or categorical variables.

Detecting missing values and outliers

  • Identify and handle missing data carefully, noting where and why values are missing; avoid blindly dropping records since this can introduce bias. Instead, consider strategies like keeping NaNs or using imputation only after understanding the cause of missingness.

  • Imputation is the process of inferring missing values using other data available in the dataset. Here are some common imputation methods: average imputation (replace missing values with the average value for that field), regression imputation (develop a model to predict missing values and replace with the predicted value from the model), and random imputation (replace missing values with random values).

Looking at summaries, distributions, and relationships between variables

  • How is the data in each variable spread? Summary statistics like the mean or standard deviation and visualizations can better clarify the shape of your data. Visualizations can be especially helpful in exploring any potential relationships between two variables or columns in your data.

5.2.6.3. Basic EDA with Pandas#

EDA is most commonly performed with pandas, a Python library for working with tabular data. Below are some common Pandas notation and functions used during the EDA process.

Getting to know the data table columns and their types

  • import pandas as pd : Pandas is shortened to pd, just like how NumPy is shorted to np.

  • df refers to “dataframe,” which is essentially the term to refer to tables.

  • pd.read_csv('INSERT YOUR FILE NAME.csv') Most datasets are comma-separated values (CSV) files, and this function loads a CSV file into an easily-manipulated dataframe format.

  • df.shape Returns the # rows x # columns in the dataframe

  • df.dtypes Returns the data types for each column

Manipulating the data

  • df.sort_values(by='COL', ascending=True) Sorts rows by the values in column 'COL'.

  • df.groupby(by='COL') “Categorizes” the table based on unique values in the column 'COL', applying a function to the collected values.

  • pd.merge() Combines two or more dataframes together based on common values in columns

Detecting missing values and outliers

  • df.isna() Returns a dataframe with True / False values indicating whether a value is missing (None or NaN)

  • df.dropna() Drops rows with missing data

  • df.fillna(VALUE) Fills missing values with the passed in VALUE

Looking at summaries, distributions, and relationships between variables

  • df.describe() Returns summary statistics for all numeric columns

  • df['col'].mean(), df['col'].min(), and df['col'].max() summarize a selected numerical column.


5.2.7. 🎉 Recap#

You’ve covered a lot of ground! Here’s a summary of everything in this notebook:

Core Data Structures

  • A Series is a labeled 1D array — like a single spreadsheet column

  • A DataFrame is a labeled 2D table — like an entire spreadsheet

  • Pandas is built on NumPy — fast under the hood, and easy to convert between them

Exploration

  • df.head() / df.tail() — preview first or last rows

  • df.shape — dimensions as (rows, cols)

  • df.columns / df.index — column names / row labels

  • df.info() — column types and missing value counts

  • df.describe() — summary statistics

Selection

  • df["col"] — select a column (returns Series)

  • df[["col1", "col2"]] — select multiple columns (returns DataFrame)

  • df.loc[row, col] — select by label (inclusive slicing)

  • df.iloc[row, col] — select by integer position (exclusive slicing)

  • df[df["col"] > value] — filter rows by condition

Cleaning

  • df.isnull().sum() — count missing values per column

  • df.dropna() — remove rows/cols with missing data

  • df.fillna(value) — fill missing values

  • df.rename(columns={...}) — rename specific columns

  • df.columns.str.strip().str.lower() — bulk normalize column names

  • df.drop(columns=[...]) — remove columns

  • df["col"].str.title() — fix string capitalization

  • df["col"].replace({...}) — replace specific values

  • df["col"].astype(type) — convert data type

  • df["col"].map({...}) — transform values using a dictionary

  • df.sort_values("col") — sort rows

  • df.drop_duplicates(subset="col") — remove duplicate rows

  • df.reset_index(drop=True) — rebuild a clean row index


5.2.7.1. What’s Next?#

Great next topics to explore:

  • Reading real data — pd.read_csv(), pd.read_excel(), pd.read_json()

  • Merging datasets — pd.merge(), pd.concat()

  • Pivot tables — df.pivot_table()

  • Time series — pd.to_datetime(), .resample()

  • Visualization — df.plot(), Matplotlib, Seaborn