Python Pandas for Data Analysis: Getting Started Guide (2026)
Learn Python Pandas for data analysis from scratch. DataFrames, filtering, groupby, merging, data cleaning, and 5 one-liners every data analyst should know.
Pandas is the most-used Python library for data analysis. If you're becoming a data analyst and already know some SQL, Pandas is the natural next step — it lets you do everything SQL does, plus visualization, statistical analysis, and automation.
This guide takes you from zero to productive with Pandas. Every example uses real-world data scenarios, not toy datasets. For a structured 12-week study plan, explore our Data Analyst Roadmap 2026.
Practice every concept in this guide on Topfolio Practice. We have interactive Python and SQL questions with instant feedback — no setup required.
Why Pandas?
Pandas appears in 85%+ of data analyst job listings that mention Python. Here's why:
- SQL-like operations — Filtering, grouping, joining, aggregating — all familiar concepts
- Data cleaning — Handle missing values, duplicates, type conversions in a few lines
- File I/O — Read CSV, Excel, JSON, SQL databases, APIs
- Integration — Works with matplotlib, seaborn, scikit-learn, and every major Python library
If you know SQL, you already understand 70% of what Pandas does. The syntax is different, the concepts are the same.
Setup
# Install
pip install pandas
# Import (the standard convention)
import pandas as pd
import numpy as npThat's it. No database setup, no server configuration. Pandas works locally on any computer.
DataFrames — The Core Concept
A DataFrame is a table. Rows and columns, just like a SQL table or an Excel spreadsheet.
Creating a DataFrame
# From a dictionary
data = {
'name': ['Alice', 'Bob', 'Charlie', 'Diana'],
'department': ['Engineering', 'Marketing', 'Engineering', 'Marketing'],
'salary': [85000, 72000, 92000, 68000],
'years_exp': [5, 3, 8, 2]
}
df = pd.DataFrame(data)| name | department | salary | years_exp | |
|---|---|---|---|---|
| 0 | Alice | Engineering | 85000 | 5 |
| 1 | Bob | Marketing | 72000 | 3 |
| 2 | Charlie | Engineering | 92000 | 8 |
| 3 | Diana | Marketing | 68000 | 2 |
Reading Data From Files
# CSV (most common)
df = pd.read_csv('sales_data.csv')
# Excel
df = pd.read_excel('report.xlsx', sheet_name='Q1')
# SQL database
import sqlite3
conn = sqlite3.connect('database.db')
df = pd.read_sql('SELECT * FROM orders', conn)
# JSON
df = pd.read_json('api_response.json')Quick Data Inspection
df.head() # First 5 rows
df.tail(10) # Last 10 rows
df.shape # (rows, columns)
df.dtypes # Column data types
df.describe() # Summary statistics
df.info() # Column names, types, non-null counts
df.columns.tolist() # List of column namesSQL equivalent of df.describe(): There isn't one. In SQL, you'd write 5 separate queries for count, mean, std, min, and max. Pandas does it in one call.
Selecting and Filtering Data
Selecting Columns
# Single column (returns a Series)
df['name']
# Multiple columns (returns a DataFrame)
df[['name', 'salary']]SQL equivalent: SELECT name, salary FROM employees
Filtering Rows
# Single condition
df[df['salary'] > 80000]
# Multiple conditions (use & for AND, | for OR)
df[(df['salary'] > 70000) & (df['department'] == 'Engineering')]
# Using .query() — cleaner for complex filters
df.query('salary > 70000 and department == "Engineering"')SQL equivalent: SELECT * FROM employees WHERE salary > 70000 AND department = 'Engineering'
Filtering with isin()
# SQL: WHERE department IN ('Engineering', 'Marketing')
df[df['department'].isin(['Engineering', 'Marketing'])]Filtering with string methods
# Names containing 'li'
df[df['name'].str.contains('li', case=False)]
# Names starting with 'A'
df[df['name'].str.startswith('A')]Sorting
# Sort by salary descending
df.sort_values('salary', ascending=False)
# Sort by multiple columns
df.sort_values(['department', 'salary'], ascending=[True, False])SQL equivalent: SELECT * FROM employees ORDER BY department ASC, salary DESC
GroupBy and Aggregation
This is the Pandas equivalent of SQL's GROUP BY. If you understand one, you understand the other.
Basic GroupBy
# Average salary by department
df.groupby('department')['salary'].mean()SQL equivalent: SELECT department, AVG(salary) FROM employees GROUP BY department
Multiple Aggregations
df.groupby('department').agg(
avg_salary=('salary', 'mean'),
max_salary=('salary', 'max'),
headcount=('name', 'count'),
total_experience=('years_exp', 'sum')
)SQL equivalent:
SELECT department,
AVG(salary) as avg_salary,
MAX(salary) as max_salary,
COUNT(name) as headcount,
SUM(years_exp) as total_experience
FROM employees
GROUP BY departmentGroupBy with Transform
transform() keeps the original DataFrame shape — like a SQL window function.
# Add department average as a new column (like AVG() OVER PARTITION BY)
df['dept_avg_salary'] = df.groupby('department')['salary'].transform('mean')
# Flag employees above their department average
df['above_avg'] = df['salary'] > df['dept_avg_salary']SQL equivalent:
SELECT *,
AVG(salary) OVER (PARTITION BY department) as dept_avg_salary,
CASE WHEN salary > AVG(salary) OVER (PARTITION BY department)
THEN true ELSE false END as above_avg
FROM employeesGroupBy + transform is Pandas' answer to SQL window functions. If you're coming from SQL, this concept will feel immediately familiar.
Merging and Joining
Pandas merge works exactly like SQL JOINs.
Inner Join
# SQL: SELECT * FROM orders o JOIN customers c ON o.customer_id = c.id
orders_with_customers = pd.merge(
orders, customers,
left_on='customer_id', right_on='id',
how='inner'
)Left Join
# SQL: SELECT * FROM orders o LEFT JOIN customers c ON o.customer_id = c.id
pd.merge(orders, customers, left_on='customer_id', right_on='id', how='left')Join Types
Pandas how= | SQL Equivalent |
|---|---|
'inner' | INNER JOIN |
'left' | LEFT JOIN |
'right' | RIGHT JOIN |
'outer' | FULL OUTER JOIN |
Multiple Join Keys
pd.merge(df1, df2, on=['year', 'month', 'category'], how='left')Data Cleaning Essentials
Real-world data is messy. These operations are what you'll use most frequently.
Handling Missing Values
# Check for missing values
df.isnull().sum()
# Drop rows with any missing value
df.dropna()
# Drop rows where specific column is null
df.dropna(subset=['email'])
# Fill missing values
df['salary'].fillna(df['salary'].median(), inplace=True)
# Forward fill (use previous value)
df['price'].fillna(method='ffill', inplace=True)Removing Duplicates
# Remove exact duplicates
df.drop_duplicates()
# Remove duplicates based on specific columns (keep last)
df.drop_duplicates(subset=['email'], keep='last')
# Count duplicates
df.duplicated(subset=['email']).sum()Type Conversions
# String to datetime
df['date'] = pd.to_datetime(df['date'])
# String to numeric (errors='coerce' turns invalid values to NaN)
df['revenue'] = pd.to_numeric(df['revenue'], errors='coerce')
# Change column type
df['category'] = df['category'].astype('category') # Saves memoryString Cleaning
# Strip whitespace
df['name'] = df['name'].str.strip()
# Lowercase
df['email'] = df['email'].str.lower()
# Replace values
df['status'] = df['status'].replace({'Active': 1, 'Inactive': 0})Creating New Columns
# Simple calculation
df['annual_bonus'] = df['salary'] * 0.10
# Conditional column (like SQL CASE WHEN)
df['seniority'] = np.where(df['years_exp'] >= 5, 'Senior', 'Junior')
# Multiple conditions
df['tier'] = pd.cut(
df['salary'],
bins=[0, 60000, 80000, float('inf')],
labels=['Low', 'Mid', 'High']
)
# Apply a custom function
df['name_length'] = df['name'].apply(len)Datetime Operations
Date manipulation is one of Pandas' strongest features.
# Parse dates
df['date'] = pd.to_datetime(df['date'])
# Extract components
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['day_of_week'] = df['date'].dt.day_name()
# Filter by date range
df[(df['date'] >= '2026-01-01') & (df['date'] < '2026-04-01')]
# Resample time series (monthly totals)
df.set_index('date').resample('M')['revenue'].sum()
# Date differences
df['days_since_signup'] = (pd.Timestamp.now() - df['signup_date']).dt.daysPivot Tables
Pivot tables summarize data by two dimensions — like a cross-tab in Excel.
# Revenue by month and category
pivot = pd.pivot_table(
df,
values='revenue',
index='month',
columns='category',
aggfunc='sum',
fill_value=0
)This gives you a table where rows are months, columns are categories, and cells are total revenue.
5 One-Liners Every Data Analyst Should Know
1. Value Counts (frequency distribution)
df['category'].value_counts(normalize=True).mul(100).round(1)Gives you the percentage distribution of each category.
2. Quick correlation check
df[['price', 'quantity', 'revenue', 'discount']].corr().round(2)Instant correlation matrix — find which variables move together.
3. Find rows with any null in specific columns
df[df[['email', 'phone', 'address']].isnull().any(axis=1)]Quickly identify incomplete records.
4. Group percentages
df.groupby('department')['salary'].apply(lambda x: (x > 80000).mean() * 100)"What percentage of each department earns above 80K?"
5. Memory-efficient reading of large files
df = pd.read_csv('huge_file.csv', usecols=['id', 'date', 'amount'], dtype={'id': 'int32', 'amount': 'float32'})Only reads the columns you need with smaller data types.
Pandas vs SQL — Quick Reference
| Task | SQL | Pandas |
|---|---|---|
| Select columns | SELECT col1, col2 | df[['col1', 'col2']] |
| Filter rows | WHERE col > 5 | df[df['col'] > 5] |
| Sort | ORDER BY col DESC | df.sort_values('col', ascending=False) |
| Group + aggregate | GROUP BY col | df.groupby('col').agg(...) |
| Join | JOIN ... ON | pd.merge(..., on=..., how=...) |
| Count distinct | COUNT(DISTINCT col) | df['col'].nunique() |
| Window function | OVER (PARTITION BY) | df.groupby('col').transform(...) |
| Limit | LIMIT 10 | df.head(10) |
| Null handling | COALESCE(col, 0) | df['col'].fillna(0) |
| Case when | CASE WHEN ... THEN | np.where(...) or pd.cut() |
If you know SQL, use this table as your Rosetta Stone for Pandas.
What to Learn Next
Now that you know Pandas basics, here's the progression:
- Practice on real problems — Solve Python data analysis questions to build muscle memory
- Learn visualization — Matplotlib and Seaborn for charts (most analyst roles require this)
- Advanced Pandas — MultiIndex, .pipe(), rolling windows, method chaining
- Statistics basics — Hypothesis testing, distributions, correlation analysis
Practice Python Data Analysis
78+ free Python practice questions on Topfolio. Pandas, NumPy, data cleaning, datetime, and more — with instant feedback in a live Python editor.
Start Python PracticeFrequently Asked Questions
Why should I learn Pandas if I already know SQL?
SQL extracts and aggregates data from databases, but Pandas enables advanced in-memory data wrangling, automated data pipelines, custom transformations, statistical computing, and seamless integration with visualization tools like Matplotlib and Seaborn.
What is the core difference between a Pandas Series and a DataFrame?
A Series is a one-dimensional labeled array capable of holding any data type (equivalent to a single table column). A DataFrame is a two-dimensional tabular data structure with labeled axes (rows and columns), composed of multiple Series.
How does Pandas handle missing data compared to SQL NULL?
In Pandas, missing values are represented as NaN (Not a Number) or None. You handle them explicitly using df.isna(), df.dropna(), or df.fillna() (the equivalent of SQL COALESCE).
How much Python do I need to know before learning Pandas?
You only need basic Python fundamentals: variables, lists, dictionaries, functions, and loops. Once you have those basics, you can jump directly into Pandas DataFrames.

Written by
Founder at Topfolio with 6+ years in data & analytics across JPMC, Ultrahuman, and high-growth startups. Sat on hiring panels, reviewed 500+ resumes, and writes practical SQL & data guides.
Related Articles
Python for Data Analysis: The Complete Workflow Playbook (2026)
Master python data analysis with this complete playbook: pandas wrangling, exploratory data analysis, statistical cohorts, and production data pipelines.
Python Tutorial: The Complete Guide for Data Analysts (2026)
Master Python programming with this comprehensive python tutorial for data analysts: variables, data structures, control flow, functions, NumPy, Pandas, and real-world projects.
Python Practice Questions: 25 Real Problems & Solutions
Practice 25 real Python problems for data analytics. Solve exercises on data types, control flow, functions, lambdas, file I/O, error handling, and pandas.