Sub topic 4
Taking a First Look: shape, head, info, dtypes
This chapter covers the first checks you run on any table you have just loaded. It assumes you can run Python in a notebook or script, that pandas and matplotlib are installed, and that you know what a DataFrame and a Series are. It also assumes you loaded train.csv with pd.read_csv in the previous chapter.
The goal is a short, repeatable routine. In under a minute you should know how big the table is, what each column holds, which columns are incomplete, and whether pandas read the types correctly. Later chapters rely on these facts, so a mistake here carries forward.
Why a first look comes before any analysis
A table can load without errors and still be wrong. A numeric column may arrive as text, an identifier may be treated as a quantity, or a column may be mostly empty. If you compute averages first, you may get an error or, worse, a plausible but meaningless number.
The first look answers four questions:
- How many rows and columns are there?
- What do a few actual rows look like?
- What type did pandas assign to each column?
- How many values are present in each column?
The routine
import pandas as pd
df = pd.read_csv("train.csv")
print(df.shape)
print(df.head())
df.info()Each of the three calls answers a different question. The sections below take them in turn.
shape: the size of the table
df.shape is an attribute, not a method, so it has no parentheses. It returns a tuple of (rows, columns).
For the Titanic training file you should see (891, 12): 891 passengers and 12 columns. Record these numbers. If a later step drops rows, you can compare against 891 to see how many were lost.
A surprising shape is an early warning. If you expected 12 columns and see 1, the file probably uses a separator other than a comma, and read_csv put each line into a single column. If the row count is far from what the source documents, the file may be truncated or may include a footer line.
head: looking at real rows
df.head() shows the first five rows. Pass a number to see more, for example df.head(10). Use df.tail() to see the last rows, and df.sample(5, random_state=0) for a random sample. The sample is often more informative than head, because files are frequently sorted and the first rows may not be typical.
What to look for in the Titanic data:
PassengerIdruns 1, 2, 3, and so on. It is a row label, not a measurement.Survivedis 0 or 1. This is the outcome the tutorial studies.Pclassis 1, 2, or 3. It is a number in the file, but it names a category (ticket class).Name,Sex,Ticket,Cabin, andEmbarkedare text.AgeandFareare measurements.Agehas decimals for some passengers.CabinshowsNaNin many rows.NaN(not a number) is pandas' marker for a missing value.
Wide tables are truncated when printed. If pandas shows ... in the middle of the columns, you can raise the display limit:
pd.set_option("display.max_columns", 50)
print(df.head())This changes only how results are printed. It does not change the data.
columns and dtypes: what each column is
df.columns lists the column names. Check them for stray spaces or inconsistent capitalization, because df["Age "] and df["Age"] are different keys.
A column's dtype is the type pandas uses to store its values. You can see all of them at once:
print(df.dtypes)The common dtypes you will meet are in this table.
| dtype | Meaning | Titanic example |
|---|---|---|
| `int64` | Whole numbers, no missing values | `PassengerId`, `Survived`, `Pclass` |
| `float64` | Numbers with decimals, and the only numeric type here that can hold `NaN` | `Age`, `Fare` |
| `object` | Usually text, but can hold mixed Python objects | `Name`, `Sex`, `Cabin`, `Embarked` |
| `category` | A fixed set of labels, stored compactly | none yet; created later |
| `datetime64[ns]` | Dates and times | none in this file |
Two details matter in practice.
First, Age is float64 even though ages look like whole numbers. A plain int64 column cannot hold NaN, so when a column of integers has missing values, pandas stores it as floats. A float dtype on a column that looks like integers is therefore a hint that values are missing.
Second, in recent pandas versions text columns may be shown as str rather than object, depending on the version and settings. The meaning is the same for this chapter. Treat both as "text".
info: types and non-null counts together
df.info() prints a summary and returns None, so do not wrap it in print. Writing print(df.info()) prints the summary and then the word None.
The output looks roughly like this (spacing varies by version):
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 12 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 PassengerId 891 non-null int64
1 Survived 891 non-null int64
2 Pclass 891 non-null int64
3 Name 891 non-null object
4 Sex 891 non-null object
5 Age 714 non-null float64
6 SibSp 891 non-null int64
7 Parch 891 non-null int64
8 Ticket 891 non-null object
9 Fare 891 non-null float64
10 Cabin 204 non-null object
11 Embarked 889 non-null object
dtypes: float64(2), int64(5), object(5)
memory usage: 83.7+ KBRead it in this order:
- The header line gives the row count (891 entries).
- For each column, compare
Non-Null Countwith 891. The difference is the number of missing values. - Check that each dtype matches what the column means.
- Glance at memory usage if the file is large.
From this output you can already see the main gaps. Age has 714 non-null values, so 177 are missing. Cabin has 204, so 687 are missing. Embarked is missing 2. The next chapter measures and interprets these gaps in detail. Here the point is only to notice them.
Common errors at this stage
| Symptom | Likely cause | What to do |
|---|---|---|
| `FileNotFoundError` | Wrong working directory or path | Print `os.getcwd()`, and use a correct or absolute path |
| `shape` shows one column | Wrong separator | Pass `sep=";"` or `sep="\t"` to `read_csv` |
| A numeric column has dtype `object` | Stray text in the column, such as `"N/A"` or `"$12"` | Find the offending values, then convert with `pd.to_numeric(..., errors="coerce")` |
| `print(df.info())` shows `None` | `info()` prints on its own | Call `df.info()` without `print` |
| `df.shape()` raises `TypeError` | `shape` is an attribute | Remove the parentheses |
The numeric-as-object case deserves a closer look, since it quietly breaks later steps. Here is a small, self-contained demonstration:
import pandas as pd
raw = pd.DataFrame({"fare": ["7.25", "71.28", "unknown", "8.05"]})
print(raw.dtypes)
raw["fare_num"] = pd.to_numeric(raw["fare"], errors="coerce")
print(raw)
print(raw.dtypes)The first dtypes print shows fare as text, because one value is not a number. With errors="coerce", anything that cannot be parsed becomes NaN, and the new fare_num column is float64. Note that coercion hides the problem rather than fixing it. Check how many values became NaN before moving on.
A second look at meaning, not just types
Pandas assigns types from the file's contents, not from what the columns mean. Two Titanic columns show the gap:
Pclassisint64, but averaging ticket classes is not meaningful. It is a category. Later chapters group by it rather than averaging it.PassengerIdisint64, but it identifies a row. Summary statistics on it tell you nothing. Its correlation with other columns would also be meaningless.
Likewise Survived is stored as an integer but is really a yes or no flag. Its mean is useful because it equals the survival rate, a trick used in the grouping chapter.
A good habit is to write one line per column stating what it means and whether the dtype fits. This costs a few minutes and prevents errors later.
Wrapping the routine in a function
If you will explore several files, put the checks in one function:
import pandas as pd
def first_look(frame: pd.DataFrame, n: int = 5) -> None:
print("shape:", frame.shape)
print("\ncolumns:", list(frame.columns))
print("\nhead:")
print(frame.head(n))
print("\ninfo:")
frame.info()
first_look(pd.read_csv("train.csv"))The function only prints. It does not change the DataFrame, which is the right default for exploration.
Exercise
After loading the Titanic file, info() reports Age as float64 with 714 non-null values out of 891 rows. Give two things this tells you, and explain why Age is not int64.
Show answer
First, 891 - 714 = 177 passengers have no recorded age, so any age-based result rests on 714 rows. Second, the column is stored as floats. It is not int64 because an integer column cannot hold NaN, so pandas uses float64 when whole-number data contains missing values. The float dtype is therefore itself a hint that values are missing.
Exercise
A colleague loads a file and df.shape returns (500, 1), although the file is supposed to have 8 columns. What is the most likely cause, and how do you fix it?
Show answer
The file probably uses a separator other than a comma, such as a semicolon or tab, so each whole line landed in one column. Reload with the correct separator, for example pd.read_csv("file.csv", sep=";"), then check that shape now shows 8 columns.