Sub topic 2
Checking what was loaded
This chapter assumes you can run Python scripts or notebooks, install packages with pip, and know that a DataFrame is a table of rows and labeled columns. You should also have read the previous chapter, where read_csv first turned text into a DataFrame.
A successful call to read_csv does not mean the data is correct. pandas guesses the header, the types and the index, and it rarely raises an error when a guess is wrong. A short inspection right after loading catches most problems before they spread into later steps.
What to check after every load
Five questions cover most loading mistakes:
- Are the column names what you expected?
- How many rows and columns arrived?
- Does each column have a sensible data type?
- How many values are missing in each column?
- Do the first and last rows look like real records?
The tools below answer these in turn.
Looking at rows with head, tail and sample
head() returns the first rows, 5 by default. tail() returns the last rows. sample() returns random rows.
import pandas as pd
from io import StringIO
text = (
"id,name,signup,plan\n"
"1,Ana,2024-01-05,pro\n"
"2,Ben,2024-02-11,free\n"
"3,Cleo,2024-03-02,pro\n"
"4,Dev,2024-03-19,free\n"
"5,Eli,2024-04-07,pro\n"
"6,Fay,2024-04-30,free\n"
)
df = pd.read_csv(StringIO(text))
print(df.head(3))
print(df.tail(2))
print(df.sample(2, random_state=0))Use tail() as well as head(). Files exported from spreadsheets and reporting tools often end with a "Total" row or a footer line. Those lines load as ordinary data and will distort sums and averages if you miss them. sample() helps with sorted files, where the first rows are not typical of the rest. Passing random_state makes the sample repeatable.
Shape, columns and index
Three attributes describe the structure of the table without printing any data.
print(df.shape)
print(df.columns.tolist())
print(df.index)df.shapeis a tuple of(rows, columns). Compare it with what you know about the source. If a file has 6 data lines andshape[0]is 5, the first data line was probably consumed as a header.df.columnsholds the column labels. Look for stray spaces, odd capitalization, or labels such asUnnamed: 0. The labelUnnamed: 0appears when the file has an empty header cell, often because it was saved from a DataFrame with its index included.df.indexshows the row labels. By default this is aRangeIndexfrom 0 to n-1. If you expected an index from a column and still see aRangeIndex, theindex_colargument did not take effect.
Summarizing with info
df.info() is the most useful single call after loading. It prints the number of rows, each column's name, its count of non-null values, its dtype, and the memory used.
df.info()The output looks like this:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6 entries, 0 to 5
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 id 6 non-null int64
1 name 6 non-null object
2 signup 6 non-null object
3 plan 6 non-null object
dtypes: int64(1), object(3)
memory usage: 324.0+ bytesNote that info() prints directly and returns None. Do not wrap it in print(), or you will see an extra None.
Read the output in three passes:
- Non-Null Count. A count lower than the row count means the column has missing values. A count equal to the row count does not prove the data is complete. Empty strings and placeholders such as
"N/A"or-may have been kept as ordinary text. - Dtype. Here
signupisobject, which means pandas kept the dates as plain strings. Later chapters show how to parse them at load time. Seeingobjectfor a column that should be numeric usually means at least one value could not be read as a number. - Memory usage. For small files this is trivial. For large files it tells you whether chunked reading, covered later, is worth using. Add
memory_usage="deep"to count the real size of string data, which the default estimate understates.
Reading dtypes directly
df.dtypes returns the types as a Series, which you can filter or compare in code.
print(df.dtypes)
print(df.select_dtypes(include="number").columns.tolist())The common dtypes you will meet right after read_csv are:
| dtype | Typical meaning |
|---|---|
| `int64` | Whole numbers with no missing values |
| `float64` | Decimal numbers, or whole numbers that had missing values |
| `bool` | True/False values |
| `object` | Text, mixed content, or anything pandas could not convert |
| `datetime64[ns]` | Dates, only if you asked for date parsing |
A common surprise is an integer column that arrives as float64. Standard NumPy integers cannot hold a missing value, so a single blank cell turns the whole column into floats. The values 1, 2, <blank> become 1.0, 2.0, NaN. This is a sign of missing data, not a bug.
Counting missing values
info() shows non-null counts, but a per-column count of missing values is easier to read. Combine isna() with sum().
text = "id,score\n1,9.5\n2,\n3,7.0\n4,\n"
scores = pd.read_csv(StringIO(text))
print(scores.isna().sum())
print(scores.isna().mean())isna() gives a True/False table, and sum() counts the True values per column. mean() gives the fraction missing, which is easier to compare across files of different sizes. Here score has two missing values, which is 50 percent.
Summary statistics with describe
describe() reports count, mean, standard deviation, minimum, quartiles and maximum for numeric columns.
print(scores.describe())Use it as a sanity check on ranges, not as analysis. A maximum of 9999 in a column of ages, a negative price, or a minimum of 0 where zero is impossible often points to a placeholder code that should have been treated as missing. For text columns, add include="object" to get the count, the number of unique values and the most frequent value. A column you expected to have many distinct values but which shows 3 unique entries deserves a closer look.
A reusable inspection function
Once you have the pieces, wrap them in one function so every load gets the same checks.
import pandas as pd
from io import StringIO
def inspect(frame: pd.DataFrame, rows: int = 3) -> None:
print("shape:", frame.shape)
print("columns:", frame.columns.tolist())
print()
frame.info()
print()
print("missing values:")
print(frame.isna().sum().to_string())
print()
print("head:")
print(frame.head(rows).to_string())
print()
print("tail:")
print(frame.tail(rows).to_string())
text = "id,price,city\n1,3.5,Oslo\n2,,Rome\n3,4.25,\n"
inspect(pd.read_csv(StringIO(text)), rows=2)Printing with to_string() avoids the truncated display that pandas uses for wide tables.
Common problems and what they look like
The inspection tools show distinct symptoms for the usual loading errors.
| Symptom | Likely cause |
|---|---|
| `Unnamed: 0` column | File was saved with its index; use `index_col=0` |
| All data in one column | Wrong separator; check `sep` |
| Column names are actual data values | File has no header; use `header=None` |
| Numeric column has dtype `object` | Non-numeric text, thousands separators or a placeholder in the column |
| Leading zeros missing from codes | Numeric inference; set the dtype to string |
| Last row is a total | Footer line in the file; drop it or limit rows |
Each of these has a fix in a later chapter. The point here is recognizing them quickly.
Looking for placeholders and unexpected values
When a column has the wrong dtype, find the offending values. pd.to_numeric with errors="coerce" turns anything unreadable into NaN, so you can compare it with the original.
text = "id,qty\n1,10\n2,12\n3,n/a\n4,8\n"
raw = pd.read_csv(StringIO(text))
print(raw.dtypes["qty"])
converted = pd.to_numeric(raw["qty"], errors="coerce")
bad = raw.loc[converted.isna() & raw["qty"].notna(), "qty"]
print(bad.unique())The column loads as object because of n/a. The mask finds rows where the original had a value but conversion failed. The output is ['n/a']. Once you know the exact markers, you can pass them to na_values when reading, which later chapters cover.
For text columns, value_counts(dropna=False) lists each distinct value with its count, including missing ones, and quickly shows typos and inconsistent labels such as Pro and pro.
Putting inspection in a workflow
Run the inspection straight after each load, before any transformation. If something is wrong, fix it in the read_csv call, not afterward with patches. Fixing at load time is simpler to repeat and keeps the loading step in one place.
Exercise
A file loads with df.shape == (200, 5). df.info() shows a price column with dtype object and 200 non-null values. What does this tell you, and how can you list the values that stop pandas from reading the column as numbers?
Show answer
There are no truly missing values, but at least one entry in price is text that pandas could not parse as a number, such as n/a, a currency symbol or a thousands separator. Convert with pd.to_numeric(df["price"], errors="coerce"), then select the rows where the converted value is NaN and the original is not null, for example df.loc[converted.isna() & df["price"].notna(), "price"].unique().
Exercise
You load a CSV whose last line is Total,,15230. Which inspection call is most likely to reveal it, and why is it important to find it before computing statistics?
Show answer
df.tail() shows the last rows, including the total line. The total loads as a normal row, so sums, means and counts would include it and give inflated or wrong results.