pandas Tutorial
Load, clean, reshape and analyze tables of data in Python.
Getting started5 lessons
- 1pandas Introductionpandas is the standard Python library for tables of data.
- 2pandas Get StartedInstall pandas with pip install pandas and import it as pd.
- 3Series versus DataFrameA Series is one labelled column and a DataFrame is a table of Series sharing an index.
- 4Shape, dtypes and infoshape gives rows and columns, dtypes lists column types and describe summarises numbers.
- 5head, tail and samplehead shows the first rows, tail the last and sample picks random rows.
Series12 lessons
- 6Create a SeriesA Series is a one dimensional labeled array.
- 7Series Index and LabelsEach Series value has a label.
- 8Series ArithmeticArithmetic on Series is vectorized and aligns on the index.
- 9Series StatisticsSeries have methods such as sum, mean, median, std, min, max and describe.
- 10Data TypesEvery Series has one dtype such as int64, float64, bool or str.
- 11Apply and Mapmap and apply run a function on each value.
- 12Series with a Custom IndexA Series can have labels instead of numbers.
- 13Series ArithmeticOperations work element by element and align on the index.
- 14Series Methodssum, mean, min, max, count, unique, value_counts and sort_values summarise a Series.
- 15apply and mapapply runs a function on every item and map replaces values with a dictionary.
- 16Boolean SeriesComparisons give True or False for each item.
- 17Describing Datadescribe gives count, mean, std, min, quartiles and max.
DataFrames19 lessons
- 18Create a DataFrameBuild a DataFrame from a dict of lists (columns), a list of dicts (rows) or a list of list.
- 19Shape, Columns and Typesshape gives (rows, columns), columns lists names, dtypes lists types and info prints a sum.
- 20Head, Tail and Samplehead shows the first rows, tail the last rows and sample draws random rows.
- 21Summary Statisticsdescribe summarizes numeric columns with count, mean, std and quartiles.
- 22Add and Change ColumnsAssign to a new column name to add it.
- 23Drop Rows and Columnsdrop removes labels.
- 24Rename Labelsrename changes column or index labels with a dict.
- 25Sort Valuessort_values orders rows by one or more columns.
- 26Set and Reset the Indexset_index makes a column the row label and reset_index turns it back into a normal column.
- 27Iterate Over RowsLooping over rows is slow.
- 28Creating DataFramesBuild from a dict of lists, a list of dicts or a NumPy array.
- 29Adding and Removing ColumnsAssign a new column with [] and remove with drop.
- 30Renamingrename changes column or index labels.
- 31Sortingsort_values sorts by columns and sort_index sorts by labels.
- 32Unique and Duplicatesdrop_duplicates removes repeated rows and duplicated marks them.
- 33Setting the Indexset_index makes a column the index and reset_index moves it back.
- 34Iterating Rowsiterrows gives rows and itertuples is faster.
- 35Totals by Row and Columnsum and mean take an axis: 0 works down columns and 1 across rows.
- 36where and clipwhere keeps values that match and replaces others.
Selecting data15 lessons
- 37Select ColumnsUse df["col"] for a Series and a list of names for a DataFrame with several columns.
- 38Select with locloc selects by label for rows and columns.
- 39Select with ilociloc selects by integer position, like Python slicing, so the end is excluded.
- 40Filter RowsA boolean condition gives a mask.
- 41Combine ConditionsCombine conditions with & (and), | (or) and ~ (not).
- 42isin and betweenisin checks membership in a list.
- 43query and wherequery filters with a string expression, which reads cleanly.
- 44Fast Scalar Accessat and iat read or write a single cell quickly, by label or position.
- 45Selecting ColumnsUse df["a"] for one column and df[["a", "b"]] for several.
- 46loc and ilocloc selects by labels and iloc by integer positions.
- 47Filtering with ConditionsCombine conditions with & and | and wrap each in parentheses.
- 48isin and betweenisin tests membership and between tests a range.
- 49queryquery filters with a string expression.
- 50nlargest and nsmallestGet the top or bottom rows by a column.
- 51copy and Chained AssignmentUse .copy() when you change a slice and use loc for assignment to avoid warnings.
Cleaning data17 lessons
- 52Find Missing ValuesMissing numbers appear as NaN and missing text as NA.
- 53Fill Missing Valuesfillna replaces missing values with a constant, a column statistic or a previous value (ff.
- 54Drop Missing Valuesdropna removes rows (or columns) with missing values.
- 55Find Duplicatesduplicated marks repeated rows.
- 56Change Data Typesastype converts a column.
- 57Replace Valuesreplace swaps values for others.
- 58String MethodsThe .str accessor applies string methods to every value: lower, upper, strip, contains, re.
- 59apply on Rows and Columnsapply runs a function on columns (axis=0) or rows (axis=1).
- 60Clip, Round and Cut Valuesclip limits values to a range and round rounds.
- 61Missing ValuesNaN marks missing values.
- 62Filling StrategiesFill with a constant, the mean or the previous value.
- 63Changing Typesastype converts a column.
- 64String MethodsThe .str accessor applies string methods to a column.
- 65replacereplace swaps values anywhere in a Series or DataFrame.
- 66Spotting OutliersUse describe, quantiles or z-scores to find unusual values.
- 67Binning with cutcut puts numbers into labelled bins.
- 68Categorical DataThe category dtype saves memory for repeated labels.
Reading and writing13 lessons
- 69Read CSVread_csv loads a CSV file or any text buffer into a DataFrame.
- 70Write CSVto_csv writes a DataFrame as text.
- 71Read and Write JSONread_json loads JSON text.
- 72Excel and Other Formatsread_excel and to_excel need the openpyxl package.
- 73Read from SQLread_sql runs a query and returns a DataFrame.
- 74CSV Round Tripto_csv writes and read_csv reads.
- 75read_csv Optionssep, header, names, usecols, dtype and parse_dates tune reading.
- 76JSON Input and Outputto_json and read_json move data to and from JSON.
- 77Excel and SQL Notesread_excel needs openpyxl and read_sql needs a connection.
- 78Working with DatesThe dt accessor reads year, month and weekday.
- 79resampleresample groups time series into periods such as months.
- 80Display Optionsset_option controls rows, columns and decimals shown.
- 81apply on Rowsapply with axis=1 runs a function per row.
Grouping and combining19 lessons
- 82Group Bygroupby splits rows by a key, applies a function to each group and combines the results.
- 83Aggregate Several Waysagg takes several functions or named aggregations, so you can compute many statistics in o.
- 84Count Valuesvalue_counts counts each distinct value.
- 85Pivot Tablespivot_table summarizes data in a grid: rows, columns, values and an aggregation function.
- 86Concatenateconcat stacks DataFrames vertically (axis=0) or side by side (axis=1).
- 87Merge (SQL style join)merge combines tables on key columns like a SQL join.
- 88Left, Right and Outer Joinshow= controls which rows are kept.
- 89join and Index Alignmentjoin combines tables on their index.
- 90Crosstab and Counting Pairscrosstab counts how often combinations of two columns occur.
- 91Dates and Timesto_datetime parses text into datetimes.
- 92Date Rangesdate_range builds a regular sequence of dates.
- 93groupbygroupby splits rows into groups, applies a function and combines the result.
- 94Several Aggregationsagg runs several functions at once.
- 95pivot_tablepivot_table summarises data in a grid with rows, columns and a function.
- 96mergemerge joins two tables on a key like SQL joins.
- 97concatconcat stacks DataFrames vertically or side by side.
- 98Cumulative and Rollingcumsum, cumprod and rolling windows track change over time.
- 99rank and shiftrank gives positions and shift moves values down for comparisons.
- 100Frequency Tablesvalue_counts with normalize gives shares and crosstab counts pairs.
Advanced pandasPremium12 lessons
- 101MultiIndexA MultiIndex uses several levels as row labels.
- 102transform and filter in Groupstransform returns a result with the original shape, so you can add group statistics back a.
- 103Rolling Windowsrolling computes statistics over a moving window, such as a 3 day average.
- 104Resample Time Seriesresample changes the frequency of a time indexed Series: for example daily values into mon.
- 105Melt and Stackmelt turns wide tables into long ones, which most tools prefer.
- 106Categorical DataThe category dtype stores repeated text as integer codes.
- 107Shift, Diff and Percent Changeshift moves values down, diff subtracts the previous value and pct_change gives growth rat.
- 108Rank and Quantile Binsrank orders values and handles ties.
- 109Split and Explode Listsstr.split turns text into lists and explode puts each list item on its own row.
- 110merge_asof and Nearest Matchesmerge_asof joins on the nearest earlier key, for example matching trades to the latest pri.
- 111Weighted and Custom Windowsewm gives recent values more weight, which makes smooth averages that react quickly.
- 112Rank Within Groupsgroupby combined with rank, cumsum or head gives per group rankings, running totals and to.
pandas in practicePremium9 lessons
- 113Method Chaining and pipeChain methods so each step reads top to bottom, with no temporary variables.
- 114Reduce MemoryCheck memory_usage(deep=True).
- 115Vectorize Instead of LoopingColumn operations run in compiled code and are far faster than Python loops.
- 116Copy on WriteIn pandas 3 every derived object behaves like an independent copy, so changing a slice nev.
- 117Testing DataFramespandas.testing provides assert_frame_equal and assert_series_equal.
- 118pandas for SQL UsersMost SQL ideas map directly: SELECT is column selection, WHERE is filtering, GROUP BY is g.
- 119Plotting with pandasDataFrame.plot draws charts with Matplotlib: line, bar, hist, box and scatter.
- 120A Small Data Cleaning ProjectA typical workflow: load, inspect, clean types, handle missing values, derive columns, gro.
- 121pandas Best PracticesKeep data in columns not variables, use vectorized code, set dtypes when reading, avoid ch.