Skip to content

pandas head() and tail(): Examples, Negative n and Top Rows

pandas head() and tail() let you inspect the first or last rows of a DataFrame or Series without printing every record. By default, each returns five rows; head(3) returns the first three, while tail(2) returns the last two. These methods select rows by their current position, not by the numeric value of their index labels or by the highest/lowest values in a column.

Quick syntax and behavior

df.head(n=5)
df.tail(n=5)
CommandRows returned
df.head()First 5 rows
df.head(2)First 2 rows
df.tail(2)Last 2 rows
df.head(0)Empty DataFrame, same columns
df.head(-2)All except last 2 rows
df.tail(-2)All except first 2 rows

The argument n is optional and should be an integer. Negative values are supported: head(-2) means “everything except the last two rows,” and tail(-2) means “everything except the first two rows.” If n is greater than the number of rows, all rows are returned; head(0) and tail(0) return empty objects with the same columns. These behaviors are documented for recent pandas versions.

Self-contained pandas example: Sales data

The older version of this article depended on an unavailable CompleteCricketData.csv file. This revised example creates its own small DataFrame and works without downloading any dataset. The Python output was checked with pandas 2.2.3.

import pandas as pd

sales = pd.DataFrame({
    "Product": ["Pen", "Notebook", "Bag", "Bottle", "Pencil", "Folder"],
    "Price": [10, 40, 500, 120, 5, 30],
    "Quantity": [3, 2, 1, 2, 6, 4]
})
sales["Revenue"] = sales["Price"] * sales["Quantity"]

print(sales.head(2))
#     Product  Price  Quantity  Revenue
# 0       Pen     10         3       30
# 1  Notebook     40         2       80

print(sales.tail(2))
#   Product  Price  Quantity  Revenue
# 4  Pencil      5         6       30
# 5  Folder     30         4      120

Use this method to confirm that files loaded correctly, column names have the expected spelling, and calculated columns such as Revenue contain plausible values. A quick preview is useful but does not validate every row.

How head() differs from tail()

head() starts at the first row in the DataFrame’s existing order; tail() starts at the end. Neither method sorts rows. After you filter or sort a DataFrame, these methods operate on the rows in that new order. The row labels displayed at the left are preserved unless you explicitly reset the index.

The original PickupBrain video is preserved above. Its sample file and interface may differ from current pandas, but the basic head/tail behavior is unchanged.

Find the largest values: sort before head()

A frequent mistake is treating df.head(5) as the five largest or best records. It merely returns the first five in current order. To see the highest revenue records, sort by that value first:

top_two = sales.sort_values("Revenue", ascending=False).head(2)
print(top_two[["Product", "Revenue"]])
#   Product  Revenue
# 2     Bag      500
# 3  Bottle      240

For large datasets where you want the largest numeric values, df.nlargest(2, "Revenue") is another option; both sort/order operations have different semantics from a plain head().

Preview a Series or a file loaded with read_csv()

revenues = sales["Revenue"]
print(revenues.head(3).tolist())  # [30, 80, 500]
print(revenues.tail(2).tolist())  # [30, 120]

# For your own CSV file, use:
# df = pd.read_csv("your_file.csv")
# print(df.head())
# print(df.tail())

In pandas, the DataFrame holds rows and columns, while a Series is one-dimensional. Both support head() and tail(). For loading CSV files, the path must point to a file that actually exists; the old cricket filename was merely an example.

Common questions and troubleshooting

  • Why does head() show rows 4–8 instead of 0–4? Your DataFrame has retained old index labels after filtering. Use reset_index(drop=True) if you want a new sequential index.
  • Does head() modify the source? No. It returns a new selection; ordinary preview calls leave the original unchanged.
  • Why are some columns truncated? pandas display settings may abbreviate wide tables. Access needed columns explicitly, or adjust display options for inspection.
  • Why are rows not in date or numerical order? These methods do not sort. Sort first with sort_values() or sort_index() as appropriate.
  • Are head() and tail() performance benchmarks? No. A preview helps with debugging but cannot prove data quality, representative distribution, or correctness of every record.

Conclusion

Use head() for a fast beginning-of-table preview and tail() for an end-of-table preview. Both accept a row count and preserve current row order. To inspect labels, sorting and row selection more deeply, see the pandas DataFrame index tutorial and the official pandas head() reference and tail() reference.

2 thoughts on “pandas head() and tail(): Examples, Negative n and Top Rows”

Leave a Reply

Your email address will not be published. Required fields are marked *