Pandasdrill

Selecting and filtering Updated November 2026

head, tail and sample

df.head(n) returns the first n rows (5 by default), df.tail(n) the last n, and df.sample(n) n random rows. Pass random_state to sample for a repeatable pick and frac=0.1 to take 10 percent of the rows.

Syntax

df.head(n=5)   |   df.tail(n=5)   |   df.sample(n=None, frac=None, random_state=None, replace=False)
PartWhat it is
nNumber of rows
fracsample: fraction of rows instead of a count
random_statesample: integer seed for reproducible results
replacesample: True allows the same row to be picked twice

Examples

import pandas as pd

df = pd.DataFrame({"id": range(1, 11), "value": range(10, 110, 10)})
df.head(3)

Result: id value 0 1 10 1 2 20 2 3 30

df.tail(2)

Result: id value 8 9 90 9 10 100

df.sample(3, random_state=1)

Result: id value 2 3 30 9 10 100 6 7 70

Same seed, same three rows every run.

Common mistakes

  • head(-3) is valid and returns all rows except the last three, which can surprise; use head(3) for the first three.
  • sample(n) larger than the row count raises ValueError unless replace=True.
  • Output is truncated with ... in the middle: set pd.set_option("display.max_rows", 100) or print df.to_string().

Practice head, tail and sample

These drills check your answer on live data, free, no account needed.

  • Pick two columnsFrom the `emp` table, keep only the `name` and `salary` columns, in that order. The result is a DataFrame with every row.
  • Position-based slicing with ilocReturn the first three rows and the first two columns of `emp`, selected by position with `.iloc`.

Questions

How do I see all columns of a wide DataFrame?

pd.set_option("display.max_columns", None) shows every column; pd.set_option("display.width", 200) widens the output.

How do I get a quick overview of a DataFrame?

df.info() lists columns, non-null counts and dtypes; df.shape gives (rows, columns); df.describe() gives statistics.

Related

  • 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.
  • describeWhat df.describe returns in pandas: count, mean, std, min, quartiles and max for numeric columns, including text columns, custom percentiles and transposing.
  • 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.
  • 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.

Previous: describeNext: set_index and reset_index