Sub topic 2
Previewing data with head and tail
This chapter covers head and tail, the two methods you use to look at the first and last rows of a DataFrame. They are the quickest way to confirm that a file loaded the way you expected.
It assumes you know basic Python syntax, have pandas installed and imported as pd, and understand that a DataFrame is a table of rows and labelled columns. Later chapters cover info and describe.
Why look at rows first
Summary statistics hide the shape of individual records. A column of dates stored as text, a header row repeated in the middle of the data, or a stray "Total" line at the bottom all look harmless in aggregate numbers. They are obvious when you read a few real rows.
head shows rows from the start and tail shows rows from the end. Neither changes the DataFrame. Both return a new, smaller DataFrame, and Jupyter or the console then displays it.
The example data
The examples in this chapter use a small table with one missing age.
import numpy as np
import pandas as pd
df = pd.DataFrame({
"name": ["Ana", "Ben", "Cleo", "Dev", "Eli"],
"age": [34, 28, np.nan, 45, 39],
"city": ["Lima", "Oslo", "Lima", "Pune", "Oslo"],
"salary": [52000, 48000, 61000, 75000, 58000],
})Each row has an index label. Here the labels are the default integers 0 to 4. head and tail keep those labels, and that matters later in the chapter.
Using head
head(n) returns the first n rows. The default is n=5, so calling df.head() on this five-row table returns every row. Pass a number to ask for fewer.
print(df.head(3)) name age city salary
0 Ana 34.0 Lima 52000
1 Ben 28.0 Oslo 48000
2 Cleo NaN Lima 61000Two details are visible in this output:
- The
agecolumn prints as34.0andNaN. A column that containsNaNis stored as floating point, so whole numbers gain a decimal point. That is a small clue that something is missing, even though you only asked for a preview. - The row labels 0, 1, 2 come from the index, not from a counter that
headcreates.
Using tail
tail(n) returns the last n rows, also defaulting to 5. The rows keep their original order. They are not reversed, so the final row of the DataFrame is the final row of the output.
print(df.tail(2)) name age city salary
3 Dev 45.0 Pune 75000
4 Eli 39.0 Oslo 58000The labels 3 and 4 are the labels these rows had in df. tail does not renumber from 0.
Choosing n, including unusual values
The argument n accepts more than small positive integers. The following table lists each case, using the five-row df.
| Call | Result |
|---|---|
| `df.head(3)` | First 3 rows |
| `df.head(100)` | All 5 rows. No error when `n` exceeds the length |
| `df.head(0)` | No rows, but the column names are kept |
| `df.head(-3)` | All rows except the last 3 (rows 0 and 1) |
| `df.tail(-4)` | All rows except the first 4 (row 4 only) |
A negative n reverses the meaning. head(-k) drops the last k rows and returns the rest, and tail(-k) drops the first k rows. This is a compact way to remove a known number of trailing or leading rows, but it is easy to misread in code review. A comment or an iloc slice is often clearer.
head(0) is useful for a different reason. It returns an empty DataFrame that still carries the column names and dtypes:
print(df.tail(0))Empty DataFrame
Columns: [name, age, city, salary]
Index: []Using head and tail on a single column
A Series, which is one column of a DataFrame, has the same two methods with the same defaults.
print(df["salary"].tail(2))3 75000
4 58000
Name: salary, dtype: int64The output shows the index labels, the values, the column name, and the dtype. Use this when a DataFrame is wide and you only care about one field.
Chaining with other operations
Because head returns a DataFrame, you can put it at the end of a method chain to look at the result of a step without printing everything. A common use is checking the top of a sorted table.
top_paid = df.sort_values("salary", ascending=False).head(2)
print(top_paid[["name", "salary"]]) name salary
3 Dev 75000
2 Cleo 61000The labels 3 and 2 show that sorting reordered the rows but kept each row's original label. If you want a fresh 0-based index after sorting, call reset_index(drop=True).
What the first and last rows can tell you
Different problems show up at different ends of a table.
At the start of a file, look for:
- Header problems, such as column names that are really data, or a title line above the real header.
- Columns that are all
NaNbecause the delimiter or encoding was wrong. - Text in a column you expected to be numeric, or the reverse.
- Obvious formatting issues, such as dates written as
01/02/2025when you expected a standard format.
At the end of a file, look for:
- Footer or summary rows, such as "Total" or a note about the export.
- Truncated data from an interrupted export.
- New records appended by a process, when you are checking that an update ran.
Here is a footer row caught with tail. The example builds a small CSV in memory so that it runs without any file.
import io
raw = "id,amount\n1,10\n2,20\n3,30\nTotal,60\n"
csv_df = pd.read_csv(io.StringIO(raw))
print(csv_df.tail(2)) id amount
2 3 30
3 Total 60The Total line is not a record. It also forces the whole id column to be stored as text, because one value cannot be a number. head would never have shown this, because the problem is only at the bottom.
Limits of a preview
A handful of rows is a very small sample. Keep these limits in mind.
- Sorted data gives a biased preview. If a table is sorted by date,
headshows only the oldest records andtailonly the newest. Values in the middle can differ completely. For a random sample, usedf.sample(5)instead. Passrandom_stateif you need the same rows each time. - Rare problems may be absent. A bad value in one row out of a million will not appear in ten rows. Previews find structural problems well and rare ones poorly. The summary methods in the next chapters cover the rest.
- Wide tables are truncated on display. When a DataFrame has more columns than fit, pandas shows the first and last few and replaces the middle with
.... The data is intact, and only the display is shortened. You can change the limit:
pd.set_option("display.max_columns", None) # show every column
print(df.head(2))
pd.reset_option("display.max_columns") # restore the defaultTo change a setting for one block of code only, use a context manager so you do not forget to restore it:
with pd.option_context("display.max_columns", None):
print(df.head(2))Editing a preview
head and tail return a new DataFrame, but whether it shares memory with the original depends on your pandas version and settings. If you plan to modify the result, make an explicit copy so you never change df by accident and never see a SettingWithCopyWarning.
preview = df.head(3).copy()
preview["salary"] = preview["salary"] * 2
print(df["salary"].head(1).iloc[0]) # still 52000Preview, then edit a copy. Do not edit through the preview.
Previewing a file without loading all of it
For a very large CSV, loading everything just to call head is wasteful. The nrows argument of read_csv reads only the first rows:
peek = pd.read_csv(io.StringIO(raw), nrows=2)
print(peek) id amount
0 1 10
1 2 20This checks the start of the file cheaply. It cannot show you the end, because the rest of the file is never read. To see a footer, you must read the whole file or use another tool.
A routine for the first look
A short, repeatable habit keeps you from skipping steps:
- Call
df.head()and read the column names and the first values. - Call
df.tail()and read the last values. - If the data is sorted or you suspect a pattern, add
df.sample(5). - Note anything odd: decimals where you expect integers,
NaN, text in numeric columns, rows that are not records.
Then move on to the structural summary from info and the statistics from describe.
Exercise
A DataFrame orders has 1,000 rows and an index of 0 to 999. You call orders.tail(-990). How many rows come back, and which index labels do they have?
Show answer
Ten rows come back, with labels 990 to 999. A negative n in tail drops that many rows from the start (990 here) and returns the rest, in their original order and with their original labels.
Exercise
You load a sales CSV and want to check two things: that the header was read correctly, and that the file does not end with a "Grand total" row. Write the two lines of code, and explain why nrows=5 in read_csv is not enough for the second check.
Show answer
Use sales.head() to check the header and the first records, and sales.tail() to look for a footer row. nrows=5 reads only the first five rows of the file, so the end of the file is never loaded and a footer row cannot appear in the preview.