Sub topic 12
Putting it together: a first-look routine
You now know what head, tail, info, and describe each report. This chapter combines them into one routine you can run on any unfamiliar DataFrame. It also adds a few checks that catch problems the individual methods can miss.
This chapter assumes you can write basic Python functions and loops. It also assumes you have pandas installed and imported as pd, and that you know a DataFrame is a table of rows and labelled columns. Earlier chapters covered the output of each method, so this one focuses on the order of the steps and how to combine the results.
Why a routine beats ad hoc poking
Each method answers a different question, and each can hide a problem the others reveal:
| Question | Tool | What it can miss |
|---|---|---|
| Do the values look sensible to a human? | `head`, `tail` | Problems in the middle of the data |
| How big is the table, and what are the types? | `shape`, `dtypes`, `info` | Bad values inside a correctly typed column |
| How many values are missing? | `info` non-null counts, `isna().sum()` | Placeholders such as `-999` or `"N/A"` |
| What is the spread of the numbers? | `describe` | Numbers stored as text |
| What do the text columns contain? | `describe(include="object")` | Misspelled variants of the same label |
If you run the steps in a fixed order, you get the same checks every time and nothing depends on your mood or memory. The order also matters. Types come before statistics, because describe silently skips a column that has the wrong dtype.
Step 1: Preview the edges
Start with head and tail. The first rows show you the column names and what a typical record looks like. The last rows show whether the file ends cleanly. A footer line or a total row that was read in as data is a common find.
On a wide table, pandas hides middle columns behind .... Before a first look, you can lift that limit:
import pandas as pd
pd.set_option("display.max_columns", None)
pd.set_option("display.width", 120)These options change only how output is printed, not the data.
Step 2: Check structure
Next read shape and info. In info, look at three things:
- Dtype against meaning. A column called
amountwith dtypeobjectholds text, not numbers. - Non-null count against the row count. Any column with fewer non-null values than rows has missing data.
- Index range. If the range does not start at 0 or has gaps, the data was filtered or concatenated before you got it.
For tables with more than 100 columns, info condenses its output by default. Pass verbose=True to list every column.
df.info(verbose=True)Step 3: Summarize with describe
Run describe() for numeric columns. Then run describe(include="object") for text columns. In pandas 3 and later, text columns may use the str dtype by default. If include="object" selects nothing on your version, use exclude="number" instead. It works on both.
When reading the numeric summary, compare three pairs of numbers:
countagainst the row count. A smaller count means missing values.minandmaxagainst what the column should contain. A negative age or a quantity of zero is a signal.meanagainst the median (the50%row). A mean far from the median means a skewed distribution or an extreme value.
Step 4: Add the checks the methods don't do
The four methods leave gaps. These checks fill them:
- Duplicate rows.
df.duplicated().sum()counts rows that repeat an earlier row exactly. - Constant columns. A column with one unique value carries no information.
nuniquetells you. - Numbers stored as text.
pd.to_numeric(col, errors="coerce")turns anything it can parse into a number and the rest intoNaN. - Outliers by a rule. The interquartile range (IQR) rule flags values more than 1.5 × IQR beyond the first or third quartile. The IQR is Q3 minus Q1.
The routine as code
This function bundles all of the steps. It only reads the frame and never modifies it.
import numpy as np
import pandas as pd
from pandas.api.types import is_object_dtype, is_string_dtype
def flag_problems(df, k=1.5):
"""Return a list of plain-text findings about df."""
flags = []
# Missing values, as a share of rows
for col, share in df.isna().mean().items():
if share > 0:
flags.append(f"{col}: {share:.0%} missing")
# Text columns whose non-missing values all parse as numbers
for col in df.columns:
if is_object_dtype(df[col]) or is_string_dtype(df[col]):
values = df[col].dropna()
if len(values) and pd.to_numeric(values, errors="coerce").notna().all():
flags.append(f"{col}: text that looks numeric")
# Outliers by the IQR rule on numeric columns
for col in df.select_dtypes(include="number").columns:
s = df[col].dropna()
q1, q3 = s.quantile([0.25, 0.75])
iqr = q3 - q1
outside = ((s < q1 - k * iqr) | (s > q3 + k * iqr)).sum()
if outside > 0:
flags.append(f"{col}: {outside} value(s) outside {k} x IQR")
# Constant columns
for col in df.columns:
if df[col].nunique(dropna=True) <= 1:
flags.append(f"{col}: constant")
# Duplicate rows
dups = int(df.duplicated().sum())
if dups:
flags.append(f"{dups} duplicate row(s)")
return flags
def first_look(df, n=5):
"""Print a standard first look at df and return a list of findings."""
print("== Shape ==")
print(df.shape)
print("\n== Head ==")
print(df.head(n))
print("\n== Tail ==")
print(df.tail(n))
print("\n== Info ==")
df.info()
numeric = df.select_dtypes(include="number")
if not numeric.empty:
print("\n== Describe: numeric ==")
print(numeric.describe())
other = df.select_dtypes(exclude="number")
if not other.empty:
print("\n== Describe: non-numeric ==")
print(other.describe())
flags = flag_problems(df)
print("\n== Findings ==")
for line in flags or ["nothing flagged"]:
print("-", line)
return flagsTwo design choices are worth noting. The function splits numeric and non-numeric columns before calling describe, so it never depends on the default behavior of describe for mixed frames. It also returns the findings as a list, so you can log them or assert on them in a test.
Running it on a messy table
This table has four deliberate problems. The amount column is stored as text, one amount is far too large, region has a missing value, country never varies, and the last two rows are identical.
messy = pd.DataFrame({
"order_id": [1001, 1002, 1003, 1004, 1005, 1006, 1006],
"amount": ["19.99", "24.50", "18.75", "22.10", "9999", "21.00", "21.00"],
"quantity": [1, 2, 1, 3, 2, 1, 1],
"region": ["north", "south", "north", np.nan, "south", "north", "north"],
"country": ["NO"] * 7,
})
findings = first_look(messy)In the info output, amount shows dtype object, and region shows 6 non-null values out of 7 rows. The numeric describe has no amount column, because text is excluded. That absence is itself a finding. The final list reads:
- region: 14% missing
- amount: text that looks numeric
- country: constant
- 1 duplicate row(s)The outlier in amount was not caught yet. A text column can't be tested against the IQR rule. This is why the order matters: fix the dtype, then look at the statistics again.
messy["amount"] = pd.to_numeric(messy["amount"])
print(messy["amount"].describe())
print(flag_problems(messy))Now describe shows a max of 9999 against a 75% value of about 23.3. The mean is about 1446.62, far above the median of 21.0. The flag list gains amount: 1 value(s) outside 1.5 x IQR, and the "text that looks numeric" line disappears.
Edge cases and limits
- Placeholders hide missing data.
isnafindsNaNandNone, but not-999,0,"N/A", or an empty string. Look for them in theminrow ofdescribeand withdf[col].value_counts().head()on text columns. If the file uses a placeholder, tell pandas when you read it, for examplepd.read_csv(path, na_values=["N/A", "-999"]). - ID columns are not quantities.
describewill happily report the mean oforder_id. The number is meaningless. Seeing it is a hint that the column should be treated as an identifier. - Skipped columns. Datetime columns are skipped by default by
describein some versions and summarized in others. Do not rely on the default. Check the dtype ininfo. - Large frames.
head,tail,shape, anddtypesare cheap.info(memory_usage="deep")inspects every object value and can be slow on millions of rows.describeand the duplicate check scan all the data. On very large files, run the routine on a sample, such asdf.sample(100_000, random_state=0). Remember that a sample can miss rare problems. - Empty frames. An empty DataFrame has a shape like
(0, 4). The routine still runs, butdescribehas nothing useful to say. Treat a zero row count as the first finding. - Duplicates are exact matches.
duplicated()does not catch"Oslo"and"oslo ". Comparenunique()with the number of labels you expect.
A habit worth keeping
Run first_look on the raw data, write down the findings, clean, and run it again. The second run should show a shorter findings list. Anything still flagged is a decision you have either made on purpose or not made yet.
Exercise
You run the first-look routine on a sales table. info shows price as dtype object, and describe() lists only quantity and discount. What is the likely cause, how would you confirm it, and what do you do next?
Show answer
The price column probably holds numbers stored as text, such as "19.99", or it contains a stray non-numeric entry like "N/A" or "$20". describe skips it because it is not numeric. Confirm with pd.to_numeric(df["price"], errors="coerce") and compare isna().sum() before and after. If the count increases, the new missing values mark the entries that failed to parse, and df.loc[converted.isna() & df["price"].notna(), "price"] shows them. Fix or replace those entries, convert with pd.to_numeric, then run describe and the outlier check again.
Exercise
Extend flag_problems to also flag any text column in which a single value makes up more than 90% of the non-missing rows. Write the code to add inside the function.
Show answer
Add this block before return flags:
for col in df.columns:
if not pd.api.types.isnumericdtype(df[col]):
topshare = df[col].valuecounts(normalize=True).max()
if topshare > 0.9:
flags.append(f"{col}: one value makes up {topshare:.0%} of rows")
value_counts skips missing values by default, and normalize=True returns shares that sum to 1, so max() is the share of the most common value. A constant column is also caught here with a share of 100%.