Sub topic 2
Previewing data with head and tail
This chapter covers how to look at the first and last rows of a DataFrame. It assumes you know basic Python syntax, have pandas installed and imported as pd, and know that a DataFrame is a table of rows and labelled columns.
Why preview rows first
Before you compute anything, look at a few real rows. A preview shows you what the columns contain, how values are formatted, and whether the file loaded the way you expected. Summaries such as info and describe come later in this tutorial. They are easier to read once you have seen actual values.
head and tail are the two methods for this. Both return a new, smaller DataFrame. Neither changes the original.
Building a sample table
The examples use this DataFrame. One age is missing on purpose, and np.nan marks it.
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],
})The row labels are 0 to 4. This default index comes from the position of each row.
Using head and tail
head(n) returns the first n rows. tail(n) returns the last n rows. If you leave out n, both use 5.
print(df.head(3))
print(df.tail(2))Output:
name age city salary
0 Ana 34.0 Lima 52000
1 Ben 28.0 Oslo 48000
2 Cleo NaN Lima 61000
name age city salary
3 Dev 45.0 Pune 75000
4 Eli 39.0 Oslo 58000Notice that age prints as 34.0, not 34. The column holds a missing value, and pandas stores missing numbers as floats. This is the first hint of a missing value, and you got it from a simple preview.
Negative values of n
A negative n means "everything except". head(-3) returns all rows except the last three. tail(-3) returns all rows except the first three.
print(df.head(-3))
print(df.tail(-3))On our five-row table, head(-3) gives Ana and Ben. tail(-3) gives Dev and Eli. This is handy when you want to drop a known number of trailing rows, such as a totals row at the bottom of a spreadsheet export.
Why check both ends
Files often have problems at one end only. A header can repeat partway through, or a summary row can sit at the bottom. The tail call is the quickest way to catch the second case.
When the first rows mislead
If a table is sorted, the first rows are not typical. A table sorted by salary shows only the lowest salaries at the top. A random sample gives a fairer picture of the middle.
print(df.sample(2, random_state=0))sample(n) returns n randomly chosen rows. The random_state argument fixes the random seed, so you get the same rows on every run. The rows keep their original index labels, so you can see where they came from.
Common errors
- Calling
headwithout parentheses.df.headis the method object, not the data. Writedf.head(). - Expecting
headto print. In a script,df.head()on its own line shows nothing. Wrap it inprint. In a notebook, the last expression in a cell is displayed automatically. - Hidden columns. For wide tables, pandas replaces the middle columns with
.... You can raise the limit withpd.set_option("display.max_columns", None). This changes a global setting for your session. - Assuming a preview is the whole story. Five rows cannot show you a rare bad value. Use them to learn the layout, then rely on
infoanddescribefor the full column.
Summary table
| Call | Returns | Typical use |
|---|---|---|
| `df.head()` | First 5 rows | Check column names and formats |
| `df.head(10)` | First 10 rows | See more examples |
| `df.tail(3)` | Last 3 rows | Look for totals or trailing junk |
| `df.head(-2)` | All rows except the last 2 | Drop a known footer |
| `df.sample(3)` | 3 random rows | Check the middle of sorted data |
Exercise
A DataFrame df has 100 rows. What does df.tail(-98) return, and why might you also run df.sample(5) after looking at df.head()?
Show answer
df.tail(-98) returns every row except the first 98, so it returns the last 2 rows. df.sample(5) helps because head only shows the start of the table, which can be unrepresentative if the data is sorted or changes format further down. Random rows from the middle give a fairer picture.