Sub topic 12
Putting it together: a first-look routine
This chapter assumes you know basic Python, have pandas imported as pd, and have already used head, tail, info, and describe one at a time. Here you combine them into one routine that you can run on any new DataFrame.
Why a fixed order helps
Each method answers a different question. Running them in the same order every time means you ask those questions in the same order, and you are less likely to skip one.
| Step | Method | Question it answers |
|---|---|---|
| 1 | `shape`, `head`, `tail` | How big is it, and do the rows look as expected? |
| 2 | `info` | Are the dtypes right, and which columns have missing values? |
| 3 | `describe` | Are the value ranges and category counts plausible? |
| 4 | `isna().sum()` | How many values are missing in each column? |
The routine as a function
Wrapping the steps in a function keeps the order fixed. The sample data has one missing age, so you can see what each step reports.
import numpy as np
import pandas as pd
def first_look(df, n=3):
print("Shape:", df.shape)
print("\nFirst rows:")
print(df.head(n))
print("\nLast rows:")
print(df.tail(n))
print("\nStructure:")
df.info()
print("\nStatistics:")
print(df.describe(include="all"))
print("\nMissing values (count and percent):")
missing = pd.DataFrame({
"missing": df.isna().sum(),
"percent": df.isna().mean().mul(100).round(1),
})
print(missing)
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],
})
first_look(df)df.info() prints directly and returns None, so the function calls it without print. The include="all" argument makes describe cover the text columns as well as the numeric ones. For columns that do not apply, such as mean for a text column, it shows NaN.
Reading the output as a checklist
Go through the output once and tick off these items.
- Shape. Does the row count match what you expected from the source? A file with far fewer rows than expected may have been truncated.
- Head and tail. Do the first and last rows look like real records? Footer lines, totals, or repeated headers often show up in
tail. - Dtypes in
info. Numbers stored asobjectusually mean some values are text, such as"N/A"or"1,200". - Non-null counts in
info. Any count below the number of rows means missing values. Hereageshows 4 non-null out of 5, so it is also stored asfloat64, becauseNaNis a float. - Numeric
describe. Comparemin,50%, andmax. Amaxfar above the 75th percentile, or a negativeminfor something like age, is a candidate outlier. - Text
describe. Checkuniqueandtop. A column with many unique values that you expected to be a short category list may contain typos or inconsistent spelling.
Common mistakes
- Reading only
head. The first rows are often clean while problems sit in the middle or at the end. Useinfoanddescribeto see the whole column. - Trusting the mean alone. One extreme salary can pull the mean far above the median (
50%). Compare the two. - Ignoring the percent missing. Four missing values in 5 rows is a serious problem. Four missing values in 5 million rows is not. The percentage tells you which case you are in.
- Forgetting
include="all". Without it,describesilently drops text columns, and you may not notice that a column is absent from the output.
Keeping a record
Write down what you find before you start cleaning. A short list such as "age has 1 missing value (20%), city has 3 unique values, no negative salaries" gives you a to-do list for cleaning and a baseline to compare against afterwards. Run first_look again after cleaning to confirm the problems are gone.
Exercise
You run first_look on a new DataFrame with 1,000 rows. info shows a price column with dtype object and 1,000 non-null values, and describe() without arguments does not list price. What is the likely cause, and what is your next step?
Show answer
Some price values are stored as text (for example "$1,200" or "N/A"), so pandas kept the whole column as object. Plain describe() only summarizes numeric columns, so it skipped price. Next, look at the raw values with df["price"].head() or df["price"].describe() to find the offending strings, then clean them and convert the column to a numeric dtype.