3.3 Data Inspection — Understand a Dataset with Pandas
3.3 Data Inspection with Pandas
After importing a dataset into a pandas DataFrame, the next step is data inspection.
Data inspection means examining the structure, size, columns, data types, missing values, and basic statistical properties of a dataset before performing cleaning, transformation, visualization, or analysis.
- Understand the structure of the dataset.
- Check the number of rows and columns.
- Identify the available columns.
- Understand column data types.
- Detect missing values.
- Identify potential data-quality problems.
- Understand numerical distributions.
- Decide what cleaning or transformation is required.
1. Sample Dataset
Throughout this lesson, we will use a small student-performance dataset.
import pandas as pd
data = {
"Name": [
"Alice",
"Brian",
"Clara",
"David",
"Eva"
],
"Age": [
20,
21,
19,
22,
20
],
"Math": [
85,
91,
76,
88,
95
],
"Science": [
82,
89,
79,
92,
94
]
}
df = pd.DataFrame(data)
print(df)
The DataFrame contains:
- 5 rows
- 4 columns
- One text column
- Three numerical columns
2. Using head()
The head() method displays the first rows of a
DataFrame.
df.head()
By default, head() displays the first
5 rows.
print(df.head())
Example output:
Name Age Math Science
0 Alice 20 85 82
1 Brian 21 91 89
2 Clara 19 76 79
3 David 22 88 92
4 Eva 20 95 94
3. Displaying a Specific Number of Rows
You can provide a number to head() to control how many
rows are displayed.
df.head(3)
This displays the first three rows.
df.head(10)
This displays the first ten rows, or all available rows if the DataFrame contains fewer than ten.
For a very large dataset, head() is one of the
safest first commands to run because it lets you inspect a
small portion without printing the entire dataset.
4. Using tail()
The tail() method displays the last rows of a
DataFrame.
df.tail()
By default, it displays the last five rows.
You can specify the number of rows:
df.tail(3)
This displays the last three rows.
head() → beginning of the dataset
tail() → end of the dataset
5. Understanding shape
The shape attribute returns the dimensions of a
DataFrame.
df.shape
Example:
(5, 4)
The first value represents the number of rows and the second value represents the number of columns.
6. Finding Number of Rows and Columns
You can separately extract the dimensions.
rows, columns = df.shape
print("Rows:", rows)
print("Columns:", columns)
Output:
Rows: 5
Columns: 4
You can also access them individually:
print(df.shape[0]) # Rows
print(df.shape[1]) # Columns
| Expression | Meaning |
|---|---|
df.shape |
Rows and columns |
df.shape[0] |
Number of rows |
df.shape[1] |
Number of columns |
7. Inspecting Column Names
The columns attribute returns the column labels of a
DataFrame.
df.columns
Example:
Index(['Name', 'Age', 'Math', 'Science'], dtype='object')
To convert the column labels into a regular Python list:
print(df.columns.tolist())
Output:
['Name', 'Age', 'Math', 'Science']
8. Inspecting the DataFrame Index
The index attribute displays the row labels.
df.index
For the default DataFrame index, you may see:
RangeIndex(start=0, stop=5, step=1)
This means the DataFrame uses integer row labels beginning at
0.
9. Inspecting Data Types with dtypes
The dtypes attribute displays the data type of every
column.
df.dtypes
Example:
Name object
Age int64
Math int64
Science int64
dtype: object
Data types help determine what operations can be performed safely on each column.
| Typical dtype | Example Data |
|---|---|
int64 |
20, 85, 100 |
float64 |
85.5, 91.25 |
bool |
True, False |
object |
Often text in older/general pandas dtype output |
string |
String data using pandas' string dtype |
datetime64[ns] |
Date and time values |
10. Using info()
The info() method provides a compact summary of a
DataFrame.
df.info()
It typically provides information such as:
- Number of rows
- Index information
- Column names
- Number of non-null values
- Data types
- Approximate memory usage
11. Understanding info() Output
A typical output may look similar to:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Name 5 non-null object
1 Age 5 non-null int64
2 Math 5 non-null int64
3 Science 5 non-null int64
dtypes: int64(3), object(1)
Here:
- 5 entries means there are five rows.
- 4 columns means there are four variables.
- Non-Null Count tells you how many values are present.
- Dtype indicates the data type of each column.
12. Detecting Possible Missing Values with info()
Suppose a dataset contains:
data = {
"Name": ["Alice", "Brian", "Clara", "David"],
"Age": [20, 21, None, 22],
"Score": [85, 91, 78, None]
}
df = pd.DataFrame(data)
df.info()
The non-null counts may show:
Name 4 non-null
Age 3 non-null
Score 3 non-null
This immediately indicates that Age and
Score contain missing values.
info() is excellent for spotting columns whose
non-null count is lower than the total number of rows.
13. Using describe()
The describe() method generates descriptive statistics
for suitable columns.
df.describe()
For numerical columns, the output commonly includes:
- count
- mean
- std
- min
- 25%
- 50%
- 75%
- max
14. Understanding describe() Statistics
| Statistic | Meaning |
|---|---|
count |
Number of non-missing observations. |
mean |
Arithmetic average. |
std |
Standard deviation. |
min |
Minimum value. |
25% |
First quartile (Q1). |
50% |
Median (Q2). |
75% |
Third quartile (Q3). |
max |
Maximum value. |
15. Example of describe()
df = pd.DataFrame({
"Math": [85, 91, 76, 88, 95],
"Science": [82, 89, 79, 92, 94]
})
print(df.describe())
A typical result will contain statistics for both numerical columns.
The 50% row represents the median, while
25% and 75% represent the first and
third quartiles.
16. Describing Categorical Data
By default, describe() focuses on numerical columns
when numerical data is available.
You can explicitly request information about object/string columns.
df.describe(
include=["object"]
)
For categorical/text data, useful statistics can include:
- count
- unique
- top
- freq
17. Describing Multiple Data Types
You can request descriptive information across different column types using:
df.describe(
include="all"
)
The exact statistics shown depend on the data types present in the DataFrame.
18. Counting Non-Missing Values
The count() method returns the number of non-missing
values in each column.
df.count()
This is useful when you want a quick column-by-column view of data availability.
19. Checking Missing Values with isna()
The isna() method identifies missing values.
df.isna()
It returns Boolean values:
True→ missing valueFalse→ value is present
To count missing values in each column:
df.isna().sum()
Example:
Name 0
Age 1
Math 0
Science 1
20. Checking Non-Missing Values with notna()
The notna() method performs the opposite logical
check.
df.notna()
Here:
True→ value is presentFalse→ value is missing
21. Checking Unique Values
The unique() method returns the distinct values in a
Series.
df["Age"].unique()
To count the number of distinct values:
df["Age"].nunique()
| Method | Purpose |
|---|---|
unique() |
Returns distinct values. |
nunique() |
Returns number of distinct values. |
22. Using value_counts()
value_counts() counts the frequency of distinct
values in a Series.
df["Age"].value_counts()
It is particularly useful for categorical columns.
Example:
20 2
21 1
19 1
22 1
Use value_counts() when you want to know how
frequently categories or individual values occur.
23. Checking Memory Usage
The memory_usage() method provides information about
the memory consumed by DataFrame columns.
df.memory_usage()
You can also request deeper memory analysis through
info().
df.info(
memory_usage="deep"
)
This can be particularly useful when working with large datasets.
24. Using T for Quick Inspection
The T attribute transposes the DataFrame, exchanging
rows and columns.
df.T
This can sometimes make a small DataFrame easier to inspect when it contains many columns.
25. Inspecting Random Rows with sample()
sample() selects random rows from a DataFrame.
df.sample()
Select multiple random rows:
df.sample(3)
This is useful when you want to inspect records that are not necessarily at the beginning or end of the dataset.
26. Inspecting Individual Columns
A specific column can be inspected using bracket notation.
df["Math"]
Multiple columns can also be selected:
df[
["Name", "Math", "Science"]
]
You can then inspect statistics for selected numerical columns:
df[
["Math", "Science"]
].describe()
27. Inspecting a Single Series
DataFrame inspection and Series inspection are related but not identical.
df["Math"].head()
df["Math"].describe()
df["Math"].dtype
df["Math"].shape
This allows focused inspection of an individual variable.
28. Complete Inspection Example
import pandas as pd
df = pd.DataFrame({
"Name": [
"Alice",
"Brian",
"Clara",
"David",
"Eva"
],
"Age": [
20,
21,
None,
22,
20
],
"Math": [
85,
91,
76,
88,
95
],
"Science": [
82,
89,
79,
92,
None
]
})
print("First rows:")
print(df.head())
print("\nShape:")
print(df.shape)
print("\nColumns:")
print(df.columns)
print("\nData types:")
print(df.dtypes)
print("\nInformation:")
df.info()
print("\nStatistics:")
print(df.describe())
print("\nMissing values:")
print(df.isna().sum())
This compact inspection routine gives a strong first understanding of the dataset before cleaning or analysis.
29. Recommended Data Inspection Workflow
A systematic inspection process is better than randomly executing methods.
-
Check the first records
Usedf.head(). -
Check the last records
Usedf.tail(). -
Check dimensions
Usedf.shape. -
Check column names
Usedf.columns. -
Check data types and non-null counts
Usedf.info(). -
Check detailed data types
Usedf.dtypes. -
Check missing values
Usedf.isna().sum(). -
Check numerical statistics
Usedf.describe(). -
Check categorical frequencies
Usevalue_counts(). -
Check representative records
Usesample().
30. Pandas Data Inspection Cheatsheet
| Command | Purpose |
|---|---|
df.head() |
First 5 rows. |
df.head(10) |
First 10 rows. |
df.tail() |
Last 5 rows. |
df.tail(10) |
Last 10 rows. |
df.shape |
Rows and columns. |
df.columns |
Column labels. |
df.index |
Row labels/index. |
df.dtypes |
Data type of each column. |
df.info() |
Compact structural summary. |
df.describe() |
Descriptive statistics. |
df.count() |
Non-missing count per column. |
df.isna().sum() |
Missing values per column. |
df.notna().sum() |
Non-missing values per column. |
df.sample() |
Random row. |
df["Column"].unique() |
Distinct values. |
df["Column"].nunique() |
Number of distinct values. |
df["Column"].value_counts() |
Frequency of values. |
df.memory_usage() |
Memory usage by index/columns. |
df.T |
Transpose DataFrame. |
31. Pandas Data Inspection Interview Questions
Q1. What is the difference between shape and
info()?
View Answer
shape returns the dimensions of the DataFrame
as (rows, columns), while
info() provides a broader structural summary
including column names, non-null counts, data types, and
memory information.
Q2. What does df.head() return?
View Answer
It returns the first five rows of the DataFrame by default.
Q3. What does df.describe() do?
View Answer
It generates descriptive statistics for suitable columns, such as count, mean, standard deviation, minimum, quartiles, and maximum for numerical data.
Q4. How can you find the number of rows and columns?
View Answer
df.shape
The first value is the number of rows and the second is the number of columns.
Q5. How can you identify missing values in every column?
View Answer
df.isna().sum()
Q6. What is the difference between head() and
tail()?
View Answer
head() displays rows from the beginning of
the DataFrame, while tail() displays rows
from the end.
Q7. How do you check the data type of every column?
View Answer
df.dtypes
Q8. How do you count unique values in a column?
View Answer
df["Column"].nunique()
32. Examination Questions
Multiple Choice Questions
Q1. What does df.shape return?
- Only the number of rows
- Only the number of columns
- Rows and columns
- Column data types
Answer: C — Rows and columns
Q2. What is the default number of rows displayed by
df.head()?
- 3
- 5
- 10
- 15
Answer: B — 5
Q3. Which method displays the last five rows by default?
last()end()tail()bottom()
Answer: C — tail()
Q4. Which method provides column data types and non-null counts?
summary()info()details()inspect()
Answer: B — info()
Q5. Which method provides statistics such as mean, median and standard deviation?
describe()statistics()stats()summary()
Answer: A — describe()
Q6. Which expression counts missing values in every column?
df.missing()df.null()df.isna().sum()df.empty()
Answer: C — df.isna().sum()
Short Answer Questions
- Define data inspection.
-
What is the purpose of
head()? -
What information does
info()provide? -
Explain the meaning of
df.shape. -
What is the purpose of
describe()? -
Differentiate between
shapeandsize. - How can you find missing values in a DataFrame?
- How can you determine the number of unique values in a column?
33. Practical Examination Questions
Question 1
Write Python statements to inspect a DataFrame named
df.
Your program should:
- Display the first five rows.
- Display the dimensions.
- Display column names.
- Display data types.
- Display DataFrame information.
- Display descriptive statistics.
Solution:
print(df.head())
print(df.shape)
print(df.columns)
print(df.dtypes)
df.info()
print(df.describe())
Question 2
Write a statement to count missing values in every column.
Solution:
print(df.isna().sum())
Question 3
Write a statement to display the frequency of values in the
Department column.
Solution:
print(
df["Department"].value_counts()
)
34. How to Interpret an Unknown Dataset
Imagine receiving a dataset that you have never seen before. Do not immediately start building charts or machine-learning models.
First answer these questions:
| Question | Useful Command |
|---|---|
| How large is it? | df.shape |
| What does it look like? | df.head() |
| How does it end? | df.tail() |
| What columns exist? | df.columns |
| What are the data types? | df.dtypes |
| Are values missing? | df.isna().sum() |
| What are the numerical statistics? | df.describe() |
| What categories occur? | value_counts() |
35. Data Inspection Best Practices
- Never assume the dataset is clean. Inspect it before analysis.
- Check dimensions first. Know how much data you are dealing with.
-
Inspect both the beginning and the end.
Use
head()andtail(). - Check data types. Incorrect types can cause analytical errors.
- Check missing values. Missing data can affect calculations and models.
- Use descriptive statistics. Understand the numerical distribution before visualization.
- Inspect categorical frequencies. This can reveal unexpected categories and imbalances.
- Do not rely on one inspection method. Each method reveals a different aspect of the dataset.
36. Quick Revision Cheatsheet
| Command | Remember It As |
|---|---|
df.head() |
Show beginning |
df.tail() |
Show ending |
df.shape |
Rows × Columns |
df.columns |
Column names |
df.index |
Row labels |
df.dtypes |
Column data types |
df.info() |
Structure + non-null + dtype |
df.describe() |
Descriptive statistics |
df.isna().sum() |
Missing-value count |
df["Col"].unique() |
Distinct values |
df["Col"].nunique() |
Number of distinct values |
df["Col"].value_counts() |
Frequency distribution |
df.sample() |
Random records |
37. Key Takeaways
-
head()displays the first rows of a DataFrame. -
tail()displays the last rows. -
shapegives the number of rows and columns. -
columnsidentifies the available variables. -
dtypesshows the data type of each column. -
info()provides a compact structural overview. -
describe()summarizes numerical data statistically. -
isna().sum()helps identify missing values. -
value_counts()helps understand categorical frequencies. - Data inspection should happen before serious data cleaning and analysis.
Before asking a dataset questions, first understand what the dataset actually contains.