Skip to content
Justice Tech School

pandas Tutorial

Load, clean, reshape and analyze tables of data in Python.

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