Sub topic 1
Inspecting a DataFrame with head, info, and describe
Prerequisites
This chapter assumes basic Python syntax, pandas installed as pd, and an understanding that a DataFrame is a table with labelled columns.
What you are inspecting: rows, columns, index, and dtypes
A pandas DataFrame contains:
- Rows, which hold individual records.
- Columns, which hold named variables.
- An index, which labels rows. By default, it contains numbers starting at 0.
- Data types, or
dtypes, which describe the kind of values in each column, such as integers, floating-point numbers, or text.
import numpy as np
import pandas as pd
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],
})Cleo's missing age makes the age column a floating-point column. Missing numeric values are commonly represented as NaN.
Previewing data with head and tail
Use head() to inspect the first rows and tail() to inspect the last rows:
print(df.head(3))
print(df.tail(2))The number inside the parentheses controls how many rows appear. These previews can reveal misspelled column values, unexpected ordering, or records that look different from the rest.
Quick facts: shape, columns, and dtypes
The shape attribute returns (rows, columns). The columns attribute lists column names. The dtypes attribute reports each column's type.
print(df.shape)
print(df.columns)
print(df.dtypes)These are attributes, so they do not use parentheses. A wrong dtype can signal a problem. For example, a date column stored as plain text cannot yet support reliable date calculations.
Reading the output of info
info() combines structural facts in one report:
df.info()
df.info(memory_usage="deep")Read its output as follows:
- The index range indicates how many row labels are present.
Non-Null Countshows how many values are present in each column.- Comparing that count with the row count reveals missing values.
Dtypereports the stored type.- The final line estimates memory use. The
deepoption examines object values more closely.
Exercise
If a DataFrame has 100 rows and a column shows 97 non-null values, what should you investigate?
Show answer
Investigate three missing values, then decide whether to remove, fill, or otherwise handle them.