AI & Data
Load, clean, explore and visualise data with Python, NumPy, pandas and friends, from first notebook to dashboards.
A path from basic Python to working analyst: environments and notebooks, SQL, NumPy and pandas, reading files and web data, cleaning, exploratory statistics and charts with Matplotlib, seaborn and Plotly. It ends with dashboards, statistics and machine learning, geospatial work and tools for data that outgrows one laptop.
The subjects follow the roadmap.sh Python Data Analysis roadmap.
Data analysis in Python means loading data, cleaning it, summarising it and turning it into charts or models, mostly in notebooks. You need only a modest slice of the language to start: control flow, a few core types and comfort with reading tracebacks.
if / elif / else branch on truthiness: 0, "", None and empty containers count as false. In pandas you rarely branch row by row; you build boolean masks or use np.where instead.
for walks any iterable and while repeats until a condition fails. Use loops for files, API pages or plotting several columns, but avoid looping over DataFrame rows: vectorised column operations are orders of magnitude faster.
print() writes any object's string form; f-strings such as f"{rate:.1%}" format numbers inline, and f"{x=}" prints the name too. In notebooks the last expression of a cell is displayed automatically, often as a rich table.
[c.strip().lower() for c in df.columns] builds a new list in one expression, with an optional if filter. Handy for renaming columns, collecting file paths or building parameter grids.
Strings are immutable; methods like split, join, strip, lower and replace return new ones. Slicing works as on lists, and "".join(parts) beats repeated += when building long text.
Operators combine values into expressions. The same symbols work element-wise on NumPy arrays and pandas columns, which is what makes vectorised analysis read like ordinary arithmetic.
+ - * / plus // (floor division), % (remainder) and ** (power). / always returns a float, even for 4 / 2. On a pandas column, df["price"] * 1.09 applies to every row at once.
==, !=, <, <=, >, >= return booleans and can be chained (0 < x < 1). Applied to a column they produce a boolean Series, the basis of row filtering. Use is only for None checks.
Plain Python uses and, or, not. Arrays and Series need &, | and ~ with parentheses around each condition, e.g. df[(df.age > 30) & (df.city == "Tehran")]; and there raises an ambiguity error.
Python's scalar types map onto the column types you meet in pandas and NumPy, though not one to one: NumPy numbers are fixed width while Python's int is unbounded. Knowing the type of a value explains most surprising results.
Python int grows as large as memory allows. In NumPy and pandas, integers are int64 and similar fixed widths that can overflow silently, and a column with missing values becomes float unless you use the nullable Int64 type.
Double-precision binary floats, so 0.1 + 0.2 != 0.3. Compare with math.isclose or np.isclose, round only for display, and reach for decimal.Decimal when exact money arithmetic matters.
True and False behave as 1 and 0 in arithmetic, so mask.sum() counts matching rows and mask.mean() gives the share that match. A very common one-liner in analysis.
Text values (str) are Unicode. pandas stores them as object by default or as the dedicated string dtype; text columns are often the messiest part of a dataset and need cleaning before analysis.
Python marks absence with None. Numeric data uses NaN (not equal to itself), datetimes use NaT, and pandas also has pd.NA. Test with pd.isna() rather than == None.
Lists, tuples, sets and dictionaries hold everything before it becomes an array or DataFrame: API responses, config, lookup tables. A DataFrame can be built straight from a list of dicts or a dict of lists.
Convert explicitly with int(), float(), str(), bool(), list(). int("3.7") raises ValueError, and bool("False") is True because the string is non-empty, a classic trap when parsing CSV flags.
Ordered, mutable sequences supporting indexing, slicing, append and sort. Fine for collecting values, but a list of numbers is slow for maths; convert to a NumPy array once you compute on it.
Immutable sequences used for fixed records and multiple return values. You meet them constantly: df.shape is a tuple, and grouping by several columns yields tuple keys.
Unordered collections of unique values with fast membership tests and |, &, - operators. Useful to compare the columns or ID lists of two datasets before merging them.
Key-value maps with fast lookup that keep insertion order. They are the shape of JSON, the input to df.rename(columns=...) and Series.map, and a natural way to build a DataFrame column by column.
Wrap repeated cleaning or plotting steps in functions so notebooks stay short and results reproducible. Methods are functions attached to an object, which is why pandas code reads as chains like df.dropna().groupby("city").mean().
def name(params): with a return value and a docstring. Prefer functions that take a DataFrame and return a new one over ones that mutate globals; they slot neatly into df.pipe(clean).
*args gathers extra positional arguments into a tuple and **kwargs gathers keyword arguments into a dict. Common for wrapper functions that forward options to pd.read_csv or a plotting call.
Single-expression anonymous functions, e.g. df.assign(ratio=lambda d: d.a / d.b) or sorted(rows, key=lambda r: r["date"]). Use a named def once the logic needs more than one line.
Always available without imports: len, range, enumerate, zip, sorted, sum, min, max, round, type, isinstance, open. help(obj) and dir(obj) explore any library object from the notebook.
A clean setup saves hours: one isolated environment per project, dependencies pinned in a file, and an editor or notebook connected to that exact environment. Most "module not found" errors come from the notebook kernel pointing at a different interpreter.
The scientific stack (NumPy, pandas, Matplotlib and friends) comes from package indexes rather than the standard library. Choose one installer per project and record its dependencies so others can recreate your results.
The standard installer from PyPI: python -m pip install pandas, pip freeze > requirements.txt to record versions and pip install -r to restore them. In a notebook, %pip install targets the running kernel.
An environment and package manager that also ships compiled non-Python libraries, which makes geospatial and GPU packages easy to install. Use the conda-forge channel and keep an environment.yml per project.
python -m venv .venv creates an isolated environment; activate it before installing. virtualenv is the faster third-party superset. Register it with Jupyter via ipykernel so notebooks see the same packages.
A very fast Rust-based manager from Astral covering Python versions, virtual environments, dependency locking and running tools. uv add pandas and uv run jupyter lab set up an analysis project in seconds.
Analysis happens mostly in notebooks, where code, output tables and charts sit together in cells. Pick one environment and learn its shortcuts; restart the kernel and run top to bottom before trusting a result, since out-of-order cells hide bugs.
The browser-based notebook environment from Project Jupyter, with tabs for notebooks, terminals and file browsing. Install it into your project environment and start it with jupyter lab.
Hosted Jupyter notebooks that need no install and offer free, time-limited GPUs. Great for learning and sharing; the runtime resets, so files must be reloaded from Drive or the web each session.
With the Python and Jupyter extensions, VS Code opens .ipynb files natively, lets you pick the kernel per notebook and adds a variable viewer, plus full editor tooling for the modules your notebooks import.
Much real data lives in relational databases, so analysts need SELECT, WHERE, GROUP BY, JOIN and ORDER BY as much as pandas. Filter and aggregate in the database when you can, and pull only the rows you need into Python.
Python talks to databases through drivers and toolkits, and pandas can turn any query result straight into a DataFrame. Always pass user input as query parameters rather than formatting it into the SQL string.
The standard-library driver for SQLite, a database stored in a single file. sqlite3.connect("data.db") plus pd.read_sql("SELECT ...", con) is the quickest way to practise SQL from Python with no server.
An in-process analytical database that runs fast SQL directly on CSV, Parquet files and even pandas DataFrames in memory. Useful when data is too big for comfortable pandas work but does not need a cluster.
The standard database toolkit: create_engine("postgresql+psycopg://...") gives a connection pool that pd.read_sql and df.to_sql accept for almost any database, and its Core and ORM layers build queries in Python.
NumPy provides the fixed-type, n-dimensional array and fast vectorised maths that pandas, SciPy, scikit-learn and Matplotlib are built on. Thinking in whole-array operations instead of loops is the key skill.
np.array, np.zeros, np.arange and np.linspace create arrays with a single dtype, a shape and a number of dimensions (ndim). reshape changes the shape without copying data when possible.
Arithmetic and universal functions (np.sqrt, np.log) apply element-wise, and reductions like sum, mean and max take an axis. Broadcasting stretches compatible shapes so matrix - matrix.mean(axis=0) just works.
Slices like a[1:5, ::2] return views that share memory, so editing them changes the original; boolean masks (a[a > 0]) and integer arrays return copies. The same idea drives .loc and .iloc in pandas.
Matrix products with @, transposes with .T, and np.linalg for inv, solve, det, eig and norm. Prefer np.linalg.solve over computing an inverse; it is faster and more numerically stable.
Create a generator with rng = np.random.default_rng(42) and draw with rng.normal, rng.integers or rng.choice. A fixed seed makes samples, shuffles and simulations reproducible.
pandas is the workhorse for tabular data: labelled columns of mixed types, fast I/O, alignment by index and a large API for selecting, grouping, joining and reshaping. Learn the idioms (vectorised operations, method chaining) rather than looping over rows.
A Series is one labelled column; a DataFrame is a table of Series sharing an index. Operations align on index labels, not position, which prevents some bugs and causes surprising NaNs when indexes differ.
The pd.read_* family (read_csv, read_excel, read_json, read_parquet, read_sql) returns DataFrames. Check the result straight away with head(), info(), dtypes and shape.
Select rows with boolean masks (df[df.sales > 100]), labels with .loc, positions with .iloc, and readable expressions with df.query("sales > 100 and region == 'EU'"). isin and between cover common cases.
Split-apply-combine: df.groupby("region")["sales"].agg(["sum", "mean"]). Named aggregation keeps output columns tidy, and transform returns a result aligned to the original rows, e.g. each row's share of its group total.
pd.merge(left, right, on="id", how="left") performs SQL-style joins and pd.concat stacks frames. Pass validate="one_to_one" or indicator=True to catch duplicate keys that silently multiply rows.
Switch between wide and long formats: melt turns columns into rows, pivot and pivot_table go the other way (the latter aggregating duplicates), and stack / unstack move index levels to columns and back.
A Rust-based DataFrame library with an expression API, multi-threaded execution and a lazy mode that optimises the whole query before running. Often much faster than pandas on large files, at the cost of a different API.
Most projects start with files on disk. Getting the read right (encoding, delimiter, header row, dtypes, date columns) avoids a long tail of cleaning problems later, so pass those options explicitly instead of trusting the defaults.
pd.read_csv handles delimiters (sep), encodings, usecols, dtype, parse_dates and chunksize for files bigger than memory. Plain text means no types are stored, so numbers with commas or odd null markers need options.
Load with the json module or pd.read_json; nested API-style records flatten into columns with pd.json_normalize. Use lines=True for newline-delimited JSON logs.
Beyond CSV and JSON, analysts constantly receive spreadsheets and increasingly store data in columnar formats. Choose a format for its type fidelity, size and read speed, not out of habit.
pd.read_excel(path, sheet_name=None) loads every sheet into a dict of DataFrames using openpyxl for .xlsx. Watch for merged header cells, totals rows and dates stored as text; df.to_excel writes results back.
A compressed, columnar binary format that stores column types, so files are smaller and much faster to read than CSV, and you can load only the columns you need. Read with pd.read_parquet via pyarrow.
Data also arrives over HTTP, from JSON APIs or HTML pages. Prefer an official API when one exists, respect rate limits and terms of use, and cache raw responses so you are not re-downloading on every notebook run.
requests.get(url, params=..., timeout=10) then resp.raise_for_status() and resp.json(). Handle pagination in a loop, pass keys in headers rather than code, and turn the collected records into a DataFrame at the end.
Parses HTML fetched with requests into a searchable tree; soup.select("table tr") uses CSS selectors to pull text and attributes. For simple HTML tables, pd.read_html may be enough on its own.
A full crawling framework: spiders follow links, pipelines clean and store items, and it handles concurrency, retries and politeness settings. Worth it for crawling many pages, overkill for a single table.
Raw data is full of gaps, typos, wrong types and impossible values, and cleaning is usually most of the work. Keep each step in code (never edit the source file by hand), log how many rows each step touches, and re-run from raw data.
First find out why values are missing, because random gaps and systematic gaps call for different handling. Then choose per column whether to drop, fill or flag them, and record that choice.
df.isna() (alias isnull) returns a boolean frame; df.isna().sum() counts gaps per column and .mean() gives the share. Sentinels like "", "N/A" or -999 are not detected until you convert them with na_values or replace.
dropna is safe when few rows are affected at random; otherwise it biases results. fillna with the median, a group mean or a constant keeps rows, and an extra "was missing" column preserves the signal.
ffill() carries the last known value forward and bfill() pulls the next one back. Suited to ordered data like sensor readings or prices; sort first, use limit= to cap gap length, and apply per group with groupby(...).ffill().
Outliers can be data-entry errors or the most interesting rows in the set. Detect them with a rule, then decide case by case whether to fix, cap, remove or keep them, and note the decision.
Take the spread of the middle half of the data (third quartile minus first) and flag anything more than 1.5 times that spread outside the box. Series.quantile([0.25, 0.75]) gives the quartiles; the rule holds up well because extremes barely move them.
Standardise with (x - mean) / std and flag values beyond about ±3. Assumes roughly normal data, and extreme values inflate the std they are measured against; scipy.stats.zscore does the computation.
Boxplots, histograms and scatterplots reveal odd values, impossible combinations and clusters that rules miss. Always look at the data before trusting a threshold-based filter.
Text columns arrive with stray spaces, inconsistent case, mixed spellings and numbers wrapped in symbols. Normalise them before grouping or joining, or "Tehran" and "tehran " will count as two cities.
The .str accessor vectorises string methods over a column: df.name.str.lower(), .str.contains("x"), .str.extract(r"(\d+)"), .str.len(). Missing values pass through as NaN instead of raising.
strip trims whitespace or given characters, replace swaps substrings (e.g. removing $ and , before converting to float), and split breaks text into parts; with expand=True pandas returns them as new columns.
Python's regular expression module for patterns too complex for plain methods, such as phone numbers or codes buried in free text. pandas .str methods accept regex too; write patterns as raw strings.
Columns often load with the wrong type: numbers as text, dates as strings, categories as free text. Correct dtypes make operations work, catch bad values early and can shrink memory use dramatically.
pd.to_datetime(col, format="%Y-%m-%d") converts text to datetimes; an explicit format is faster and avoids day/month ambiguity, and errors="coerce" turns unparseable values into NaT. Then use .dt.year, .dt.month and resampling.
df.astype({"qty": "int64"}) converts columns; it fails loudly on bad values, whereas pd.to_numeric(col, errors="coerce") turns them into NaN for inspection. Low-cardinality text cast to category saves memory.
Models need numbers, so categorical text becomes codes: one-hot columns with pd.get_dummies or scikit-learn's OneHotEncoder, or ordinal codes when categories have a natural order. Fit encoders on training data only.
EDA is getting to know a dataset before modelling or reporting: its size, types, distributions, relationships and oddities. Start with df.info() and df.describe(), then ask specific questions and answer each with a number or a chart.
Summary numbers describe the centre, spread and co-movement of variables. Always report them alongside a chart, because very different datasets can share identical summaries.
The mean is pulled by extreme values; the median (middle value) is robust to them, so skewed data like incomes is better described by the median. The mode is the most frequent value, mainly useful for categories.
Variance averages the squared distances from the mean; the standard deviation is its square root, back in the original units. Note that pandas defaults to the sample version (ddof=1) while NumPy defaults to ddof=0.
Covariance shows whether two variables move together but depends on units; correlation rescales it to −1…1. Pearson measures linear association, Spearman ranks. Correlation alone never establishes causation.
Looking at how one variable is distributed reveals skew, multiple peaks, gaps and outliers, which in turn decide whether means are meaningful and whether a transform such as a log is needed.
Bins a numeric variable and shows counts per bin. The bin width changes the story, so try several; df.col.hist(bins=30) gives a fast look and sns.histplot adds a smoothed density curve.
Draws the median, quartile box and whiskers, with points beyond the whiskers marked as potential outliers. Compact for comparing a variable across groups, though it hides multiple peaks; a violin plot shows them.
Relationships between variables suggest drivers, redundant features and segments worth digging into. Pick the tool by variable types: two numeric, two categorical, or one of each.
Plots two numeric variables as points to show trend, clusters and outliers. Colour by a third variable with hue, and lower alpha or switch to a hexbin plot when thousands of points overlap.
df.corr(numeric_only=True) computes pairwise correlations for every numeric column; render it with sns.heatmap(..., annot=True) to spot strongly related or redundant features at a glance.
pd.crosstab(df.gender, df.churned, normalize="index") counts or shares combinations of two categorical variables. A chi-squared test from scipy.stats checks whether the association is likely real.
Matplotlib is the base plotting library that pandas and seaborn draw on. Use its object-oriented API (fig, ax = plt.subplots() then ax.plot(...)) rather than the implicit plt state machine once charts get beyond a single plot.
Match the chart to the question: line for trends over time, bar for comparing categories, histogram and box for distributions, scatter for relationships. Avoid pie charts with many slices and dual axes that imply false links.
A Figure is the canvas and each Axes is one plot on it. plt.subplots(2, 2, sharex=True) returns a grid of Axes to draw on, and layout="constrained" stops labels from overlapping.
Set titles, axis labels, limits, ticks, legends and annotations through Axes methods (ax.set_title, ax.set_xlabel, ax.legend). Style sheets and rcParams apply a consistent look; seaborn themes plug into the same system.
fig.savefig("chart.png", dpi=200, bbox_inches="tight") exports a figure; use SVG or PDF for vector output that scales cleanly in reports. Call it before plt.show(), which may clear the figure.
Seaborn builds statistical charts from tidy DataFrames in one call, mapping columns to x, y, hue and facets, with sensible defaults and confidence intervals. It returns Matplotlib objects, so you can still fine-tune them.
histplot, kdeplot and ecdfplot show one variable's distribution, and displot wraps them with faceting via col= and row=. Use hue to overlay groups and stat="density" when group sizes differ.
Compare a numeric variable across categories with boxplot, violinplot, stripplot, barplot (mean with error bars) or countplot. catplot is the figure-level wrapper that adds facets.
sns.heatmap colours a 2-D table, typically a correlation matrix or a pivot table. Use annot=True for values, a diverging palette with center=0 for correlations, and mask to hide the redundant triangle.
regplot and lmplot draw a scatter with a fitted line and confidence band; order=2 fits a polynomial and logistic=True a binary outcome. Good for a visual check, not a substitute for a proper model.
Interactive charts let readers hover for values, zoom and toggle series, which helps when exploring dense data or sharing results with non-programmers. They render in notebooks and export to standalone HTML.
Plotly Express builds interactive charts from a DataFrame in one line, e.g. px.scatter(df, x="gdp", y="life", color="continent"). fig.write_html() saves a self-contained file, and the same figures power Dash apps.
A dashboard turns an analysis into something stakeholders can revisit and filter themselves. Keep it to a few key metrics, make data refresh automatic, and cache expensive queries so pages load quickly.
Turns a Python script into a web app: widgets like st.selectbox return values, and the script reruns top to bottom on each interaction. @st.cache_data avoids reloading data every time. Run with streamlit run app.py.
Plotly's framework for analytical web apps: a layout of components plus callbacks that map input changes to output updates. More explicit and flexible than Streamlit for larger, multi-page apps.
Commercial drag-and-drop BI tools common in companies. Analysts often prepare and clean data in Python, then publish it to these tools; both can also run Python scripts as data sources or visuals.
Classes help once notebooks grow into reusable tools: a loader that knows its source, a cleaner with configurable rules, or a report object. Dataclasses keep configuration tidy, and scikit-learn's fit / transform estimator pattern is a good model to copy.
After describing data, you test whether patterns are real and predict outcomes. Statistical tests quantify uncertainty; machine learning models predict from features. Both need a clear question, honest validation and attention to leakage.
Scientific routines on top of NumPy; scipy.stats is the analyst's part, with distributions, t-tests, chi-squared tests, correlation tests and more. Check a test's assumptions and report effect sizes, not only p-values.
A consistent API for classic ML: every estimator has fit and predict, and Pipeline chains preprocessing with the model. Use train_test_split and cross-validation to estimate performance on unseen data.
Location data adds questions of distance, containment and regions. Points, lines and polygons live in a coordinate reference system, and mixing systems is the most common source of wrong results.
Extends pandas with a geometry column: read shapefiles or GeoJSON with gpd.read_file, reproject with to_crs, combine layers with sjoin and draw choropleth maps with .plot(column=...).
When data outgrows one machine's memory, you either process it in chunks, switch to an out-of-core engine or distribute the work across a cluster. Try DuckDB or Polars first; a cluster adds real operational cost.
Parallelises pandas- and NumPy-like code across cores or a cluster by splitting data into partitions and building a lazy task graph that runs on .compute(). Its DataFrame API mirrors pandas closely.
The Python API for Apache Spark, the standard engine for distributed processing in data platforms. DataFrame transformations are lazy and optimised before execution, and Spark SQL lets you mix in plain SQL.
A pipeline moves data from sources through cleaning and transformation to where it is used, on a schedule and without manual steps. Make each step idempotent so it can be rerun safely, and alert on failures.
Apache Airflow defines workflows as Python DAGs of tasks with dependencies, schedules, retries and a web UI for monitoring runs. Keep heavy processing in the tasks' target systems and let Airflow orchestrate.