Sub topic 1
What you are inspecting: rows, columns, index, and dtypes
Before you call head, info, or describe, you need a clear picture of what a DataFrame is made of. Each of those methods reports on one part of that structure. This chapter names the parts, shows how to reach each one, and explains how they affect what the later inspection methods tell you.
Prerequisites
This chapter assumes you have:
- Basic Python syntax: variables, lists, dictionaries, and function calls.
- pandas installed and imported as
pd, along with NumPy asnp. - A rough idea that a DataFrame is a table of rows and labelled columns.
The examples use a pandas 2.x installation. Where pandas 3 prints something different, the text says so.
The parts of a DataFrame
A DataFrame is a two-dimensional table with labelled axes. It has four parts you will keep running into:
- Columns. Each column has a name and holds values of one type.
- Rows. Each row is one record, one value per column.
- Index. The index is the set of labels for the rows. It is separate from the data. By default it counts 0, 1, 2, and so on.
- dtypes. Each column has a dtype (data type) that tells pandas how to store and process its values.
Each column is a Series: a one-dimensional array of values with its own index and a single dtype. A DataFrame is a collection of Series that share one index. This explains why the dtype belongs to a column, not to a row or to the whole table.
A DataFrame to inspect
This chapter and the rest of the tutorial use one small DataFrame. One age is missing on purpose.
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],
})
print(type(df))
print(df.shape)
print(df.index)
print(list(df.columns))
print(df.dtypes)The output looks like this on pandas 2.x:
<class 'pandas.core.frame.DataFrame'>
(5, 4)
RangeIndex(start=0, stop=5, step=1)
['name', 'age', 'city', 'salary']
name object
age float64
city object
salary int64
dtype: objectThe sections below take each line in turn.
Shape: rows and columns
df.shape is a tuple of (number of rows, number of columns). Here it is (5, 4). The shape is an attribute, not a method, so you write it without parentheses.
The shape does not count the index as a column, and it does not tell you how much of the data is missing. len(df) gives the row count only, and df.size gives rows times columns (20 here).
print(len(df))
print(df.size)
print(df.ndim)These print 5, 20, and 2.
The index: labels for rows
When you do not give pandas an index, it builds a RangeIndex, a compact object that stores only a start, a stop, and a step. It uses almost no memory, even for millions of rows.
The index is data about the rows, not a column. It is not counted in shape[1]. You can use any column as the index:
by_name = df.set_index("name")
print(by_name.index)
print(by_name.shape)
print(by_name.loc["Ben"])After set_index("name") the shape is (5, 3), because name moved out of the columns and into the index. loc["Ben"] selects the row by label. It returns a Series whose entries are the remaining columns.
Two rules about the index cause many beginner errors:
- Labels are not positions.
locselects by label andilocselects by integer position. They agree only while the index is the default 0, 1, 2, and so on. After you filter or sort rows, the labels keep their original values, sodf.loc[2]anddf.iloc[2]can return different rows. - Labels need not be unique. An index can hold duplicate labels. Then
loc[label]returns several rows instead of one. This is legal, but it surprises people. You can check withdf.index.is_unique.
older = df[df["salary"] > 50000]
print(older.index.tolist())
print(older.iloc[1])
print(older.loc[2])The filter keeps rows with labels 0, 2, 3, and 4. Position 1 in the result is the row labelled 2, so iloc[1] and loc[2] return the same row. iloc[2] would return the row labelled 3.
Columns: names and access
df.columns is also an Index, so column names follow the same ideas as row labels. You usually get a column in one of two ways:
ages = df["age"]
print(type(ages))
subset = df[["name", "age"]]
print(type(subset))A single label gives a Series. A list of labels, even a list with one name, gives a DataFrame. This matters for inspection because Series and DataFrame have slightly different versions of the same methods, and describe is one of them. A later chapter covers Series.describe.
Attribute access such as df.age works only when the name is a valid Python identifier and does not collide with a DataFrame method. A column called count or max cannot be read as df.count. Bracket access always works, so prefer it.
Column names can contain stray spaces, such as "city " with a trailing space. This is a common cause of KeyError after loading a CSV file. Printing list(df.columns) instead of df.columns makes these spaces easier to see, because each name appears inside its own quotes.
dtypes: how each column is stored
df.dtypes returns a Series that maps each column name to its dtype. Because the dtype belongs to the column, every value in a column is stored the same way, and operations on the column are fast.
| dtype | Holds | Notes |
|---|---|---|
| `int64` | Whole numbers | Cannot store missing values in the default form |
| `float64` | Decimal numbers | Uses `NaN` for missing values |
| `bool` | `True` and `False` | No missing values in the default form |
| `object` | Anything, usually strings | Python objects, mixed types possible |
| `datetime64[ns]` | Dates and times | Missing values appear as `NaT` |
| `category` | A fixed set of labels | Saves memory for repeated values |
Pandas 3 changes the default dtype for text columns from object to a dedicated string dtype, so your name and city columns may show str there. The rest of the table is the same.
Why `age` is float64
The age list contains whole numbers and one np.nan. In the default NumPy-backed dtypes, an integer array cannot hold a missing value, because NaN is a floating-point concept. Pandas therefore stores the whole column as float64. You can see this directly:
print(pd.Series([34, 28, 45]).dtype)
print(pd.Series([34, 28, np.nan, 45]).dtype)
print(df["age"].astype("Int64").tolist())The first line prints int64 and the second prints float64. The third converts the column to the nullable integer dtype Int64 (capital I), which stores the ages as integers and shows the missing one as <NA>.
This is a good example of what dtype inspection is for. The dtype is a clue about the data. A float column that you expect to hold whole numbers often means there are missing values in it.
The `object` dtype
object is the catch-all dtype. A column of strings is object on pandas 2.x, but so is a column that mixes numbers and strings. That makes object a warning sign for numeric-looking columns:
messy = pd.DataFrame({"price": ["10", "20", "N/A", "40"]})
print(messy.dtypes)
print(messy["price"].map(type).value_counts())The price column holds text, so its dtype is object, and arithmetic or describe on it will not behave like a numeric column. One bad entry such as "N/A" is enough to stop a CSV reader from parsing the whole column as numbers. When a column you expect to be numeric shows up as object, look for stray text before you do anything else.
Checking the structure in one place
Putting these attributes together answers the first questions you should ask about any unfamiliar table:
print(f"rows={df.shape[0]}, columns={df.shape[1]}")
print(f"index unique: {df.index.is_unique}")
print(df.dtypes.value_counts())The last line counts how many columns have each dtype. For this table it reports two object columns, one float64, and one int64.
Why this matters for head, info, and describe
Each inspection method reads a different part of the structure you just met:
headandtailshow the first and last rows together with their index labels.infolists each column with its non-null count and dtype, and reports the index range and memory use.describechooses its default columns from the dtypes. Without arguments it summarizes only numeric columns, sonameandcitywould be left out of the default output here.
Knowing the dtype of each column lets you predict what these methods will show before you run them. If the output surprises you, the surprise usually points to a data problem such as a numeric column stored as text.
Common errors
- Reading
shapeas a method. Writingdf.shape()raisesTypeError: 'tuple' object is not callable. It is an attribute. - Mixing up labels and positions. After a filter or sort,
ilocandlocgive different rows for the same number. - Expecting an integer column to stay integer. One missing value turns it into
float64. - Trusting
df.colaccess. It fails for column names with spaces and for names that clash with DataFrame methods. - Forgetting the index is not a column. An index you set is not counted in
shapeand does not appear indf.dtypes.
Exercise
A DataFrame sales has 1,000 rows and a column units that you expected to contain whole numbers. sales["units"].dtype shows float64. What is the most likely explanation, and what two things could you check or do next?
Show answer
The most likely explanation is that units contains at least one missing value (NaN), because the default integer dtype cannot store missing values and pandas stores the column as float64. You can count the missing values with sales["units"].isna().sum(). If you want integers, convert the column to the nullable integer dtype with sales["units"].astype("Int64"), which keeps the missing entries as <NA>.
Exercise
You run older = df[df["salary"] > 50000] on the chapter's DataFrame. Which row does older.iloc[2] return, and which expression would return the row labelled 2?
Show answer
The filter keeps the rows labelled 0, 2, 3, and 4, so position 2 is the row labelled 3 (Dev). The expression older.loc[2] returns the row labelled 2 (Cleo). iloc uses position and loc uses label.