2. Reading and inspecting data
2.2 First look: head, tail and shape
Highlights & notes
Select lesson text to highlight it, or tap Add note.
Bookmarks
Bookmark a lesson to see it here.
Before cleaning data, look at it. Real files can have thousands of rows, so start with a small piece.
df.head()β the first 5 rows (df.head(3)for 3)df.tail()β the last 5 rowsdf.shapeβ(rows, columns)df.columns.tolist()β the column names as a list
This first look catches common problems early: a missing header, the wrong separator or extra blank rows.
Your 3-second data check
df.shapeβ how big is it?df.head()β what does it look like?df.columns.tolist()β are the names right?
df.shape has no brackets after it: itβs a property, not a method. df.shape() raises TypeError.
How it fits together
- df.shape
- df.head()
- df.columns
Step through the code
Python
import ioimport pandas as pdtext = "id,city,amount\n1,Noida,250\n2,Delhi,400\n3,Pune,150\n4,Agra,90"df = pd.read_csv(io.StringIO(text))print(df.head(2))print(df.shape)print(df.columns.tolist())
Output
id city amount 0 1 Noida 250 1 2 Delhi 400 (4, 3) ['id', 'city', 'amount']
Practice in pandas β Solved
Print the last 2 rows of df with tail.
Expected output
id city 1 2 Delhi 2 3 Pune
Reference solution
import io
import pandas as pd
text = "id,city\n1,Noida\n2,Delhi\n3,Pune"
df = pd.read_csv(io.StringIO(text))
print(df.tail(2))
Question 1 Β· Easy
Which shows the first 5 rows?
Question 2 Β· Medium
df.shape is (120, 6). How many columns are there?
Question 3 Β· Hard
What does df.shape() do?
Key takeaways
Look before you clean: shape for size, head() and tail() for a sample, columns for the header.
Save your progress
Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.
Start free Log in