pandas reference, one page per method
The pandas methods people search for, with the direct answer, the signature, examples on a small DataFrame with their output, the errors that come up, and the drills on Pandasdrill that practice each one in a real Python session.
40 methods, each with the direct answer, syntax, worked examples, the mistakes people make and the drills that practice it. Updated November 2026.
Input and output
- pd.read_csvHow to read a CSV file in pandas with pd.read_csv: separators, headers, index columns, parsing dates, selecting columns, dtypes and the errors people hit.
- to_csv and to_excelHow to export a pandas DataFrame with to_csv and to_excel: drop the index, choose separator and encoding, format floats, several sheets, append to a CSV.
Selecting and filtering
- loc vs ilocThe difference between loc and iloc in pandas: loc selects by index label and column name, iloc by integer position. Slices, lists and boolean masks.
- Filter rowsHow to filter rows in a pandas DataFrame by one or several conditions using boolean masks, with the & | ~ operators, parentheses, isin, between and query.
- DataFrame.queryHow df.query works in pandas: conditions as a string with and, or, not, in, variables with @, column names with spaces, and when to use boolean masks instead.
- isinHow to use isin in pandas to keep rows whose value is in a list, set or Series, exclude with ~, check several columns at once and avoid the type mismatch.
- sort_valuesHow to sort a pandas DataFrame with sort_values: ascending and descending, several columns with mixed order, NaN first, sort by index and reset the index.
- head, tail and sampleHow to look at a pandas DataFrame with head, tail and sample: the first or last N rows, random rows with a seed, a fraction of rows, and showing all rows.
- set_index and reset_indexHow to use set_index and reset_index in pandas: make a column the row index, go back to a plain column, drop the index, and flatten a groupby result.
- where, mask and np.whereHow to create a conditional column in pandas: np.where for if-else, np.select for several conditions, Series.where to keep values that pass a test, and mask.
- idxmax and idxminHow to find which row holds the maximum or minimum in pandas with idxmax and idxmin, pull the full row with loc, get the max per group, and idxmax vs argmax.
Grouping and aggregation
- groupbyHow groupby works in pandas: group by one or more columns, apply sum, mean, count or size, get a flat table with as_index=False, and iterate over groups.
- aggHow to use agg in pandas to compute several statistics per group, different functions per column, named aggregations with flat column names, and lambdas.
- pivot_tableHow to build a pivot table in pandas with pivot_table: index, columns, values, aggfunc, fill_value for empty cells, margins for totals, several aggregations.
- value_countsHow to count values in a pandas column with value_counts: counts sorted by frequency, percentages with normalize=True, including NaN, and two-column combos.
- pd.crosstabHow to build a contingency table in pandas with pd.crosstab: counts of one column against another, totals with margins, row or column percentages, sums.
- cumsumHow to compute a running total in pandas with cumsum, cumulative sums per group with groupby, cumulative max and count, cumulative percentages, and resets.
- rankHow to rank in pandas with rank: ascending or descending, tie methods (average, min, dense, first), ranking within groups, percentile ranks, integer output.
- cut and qcutHow to bin numeric data in pandas: pd.cut for fixed ranges with labels like age bands, pd.qcut for equal-sized quantile groups, right-closed edges and labels.
- describeWhat df.describe returns in pandas: count, mean, std, min, quartiles and max for numeric columns, including text columns, custom percentiles and transposing.
- unique and nuniqueHow to get distinct values in pandas with unique, count them with nunique, count distinct per group with groupby, handle NaN, and see counts for all columns.
- transformHow groupby transform works in pandas: broadcast a group sum or mean to each row, share of group total, group-wise normalization, and transform versus agg.
Combining and reshaping
- mergeHow to merge DataFrames in pandas like a SQL join: on a shared column, on different key names, left and outer joins, suffixes for clashing columns, validate.
- concatHow to use pd.concat in pandas to append rows from several DataFrames, add columns side by side with axis=1, reset the index, and label the source with keys.
- meltHow to use melt in pandas to turn wide data (one column per month or category) into long format with a variable and a value column, keeping id columns.
- pivotHow df.pivot works in pandas: turn a long table with key and value columns into a wide table, what index, columns and values mean, and the duplicates error.
Cleaning
- applyHow to use apply in pandas on a Series or DataFrame, with axis=1 for row-wise logic, lambdas, returning several columns, and why vectorized code is faster.
- mapHow Series.map works in pandas to recode a column with a dict or lookup Series, apply a function per value, what unmatched values become, and map vs replace.
- fillnaHow to fill NaN values in pandas with fillna: a constant, a different value per column, the column mean or median, forward and backward fill, and by group.
- dropnaHow to drop NaN rows in pandas with dropna: any or all missing, only certain columns with subset, drop columns with axis=1, thresh for a minimum of values.
- drop_duplicatesHow to remove duplicates in pandas with drop_duplicates: whole rows or a subset of columns, keep first, last or none, and finding duplicates with duplicated.
- renameHow to rename columns in pandas with rename(columns={...}), rename every column with a function like str.lower, assign df.columns, and rename the index.
- astypeHow to change a column type in pandas with astype and pd.to_numeric: text to numbers, float to int, strings, categories, nullable Int64, bad values and NaN.
- pd.to_datetimeHow to parse dates in pandas with pd.to_datetime: formats, day-first dates, coercing bad values, and extracting year, month and weekday with the dt accessor.
- str.containsHow to use str.contains in pandas to find rows containing text: case-insensitive matching, several keywords with regex, literal characters, and the NaN error.
- str.splitHow to split a string column in pandas with str.split: into separate columns with expand=True, limit the number of splits, take one part with str[0], regex.
- explodeHow to use explode in pandas to expand a column of lists or comma-separated strings into separate rows, keep other columns, reset the index, and count tags.
Time series and windows
- rollingHow to compute a moving average in pandas with rolling: window size, min_periods to avoid leading NaN, centered windows, rolling sum and std, time windows.
- shift and diffHow to use shift and diff in pandas to get the previous or next row, compute the change and percent change between periods, and lag within groups.
- resampleHow to resample a time series in pandas: monthly, weekly or daily buckets with sum or mean, upsample with ffill, use a date column with on, and new aliases.
Reading is not practicing
Every method here links to drills that check your answer on live data. All of them are free to try.
Start practicing