Sub topic 3
Quick facts: shape, columns, and dtypes
This chapter covers the attributes that describe a DataFrame's structure without printing any of its data: shape, columns, index, and dtypes. It assumes you know basic Python syntax, have pandas installed and imported as pd, and understand that a DataFrame is a table of rows and labelled columns. head and tail were covered in the previous chapter. info and describe come in the next ones.
Why check structure first
Previewing rows shows a few examples. Structure attributes answer different questions, and they cost almost nothing even on a table with millions of rows:
- How many rows and columns are there?
- What are the columns called, exactly?
- What type does pandas think each column holds?
Many later errors come from a wrong answer to one of these. A column you assumed was numeric may hold text. A column name may have a trailing space. The file may have loaded with far fewer rows than you expected.
The examples in this chapter use the same small table throughout.
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(df.head(3))
print(df.tail(2))
print(df.shape)
print(df.dtypes)The last two lines are the focus here. The output of print(df.shape) is:
(5, 4)The parts of a DataFrame
A DataFrame has three structural parts:
- Index: the row labels. By default it is a
RangeIndexcounting from 0. - Columns: the column labels, stored in an
Indexobject. - Values: the data. Each column has its own dtype, which is the data type pandas uses to store that column.
Each attribute describes a different part of the table, and none of them changes the data.
shape, size, ndim, and len
shape is an attribute, not a method. It is a tuple of (rows, columns), so you write df.shape without parentheses. Calling df.shape() raises TypeError: 'tuple' object is not callable.
rows, cols = df.shape
print(rows, cols) # 5 4
print(len(df)) # 5, the number of rows
print(df.size) # 20, rows times columns
print(df.ndim) # 2, a DataFrame always has two dimensionslen(df)returns only the row count. It is the usual choice inside loops and conditions.df.sizecounts every cell, including missing ones. It is rarely what you want when asking "how much data do I have?".df.ndimis always 2 for a DataFrame, so you will seldom need it.
shape counts rows and columns, not non-missing values. A column full of NaN still counts as a column. The next chapters cover how to count non-missing values.
Edge cases for shape
An empty DataFrame can still have columns. A filter that matches nothing returns zero rows but keeps the column structure.
empty = df[df["salary"] > 1_000_000]
print(empty.shape) # (0, 4)
print(empty.dtypes) # the dtypes are preservedA shape like (0, 4) usually means a filter was too strict or a file was empty apart from its header. Check shape after every filter, merge, or load. Merges are a common source of surprise, because an unexpected row count after a join often points to duplicate keys.
Reading the columns
df.columns is an Index of column labels. It behaves like a list in many ways: you can loop over it, test membership with in, and slice it. Convert it to a real list with .tolist().
print(df.columns.tolist()) # ['name', 'age', 'city', 'salary']
print("salary" in df.columns) # True
print(list(df.columns[:2])) # ['name', 'age']The dtype shown when you print the Index itself depends on your pandas version. It is object in pandas 2.x and str in pandas 3. This is why the examples use tolist(), which prints the same labels in both.
Column names that cause trouble
Label problems are among the most common causes of KeyError. Files exported from spreadsheets often contain:
- Leading or trailing spaces, such as
"salary ". - Inconsistent capitalization, such as
"Salary"and"salary". - Spaces inside names, which block attribute access like
df.first name.
You can see the exact labels with repr, which shows spaces that print hides.
messy = pd.DataFrame({" Name": ["Ana"], "Total Pay ": [100]})
print(messy.columns.tolist()) # [' Name', 'Total Pay ']
messy.columns = messy.columns.str.strip().str.lower().str.replace(" ", "_")
print(messy.columns.tolist()) # ['name', 'total_pay']Cleaning is outside this chapter's scope. The point here is that looking at df.columns.tolist() is how you notice the problem. Using .tolist() rather than the default Index display makes the quote marks show where each label starts and ends.
The index
df.index completes the picture. For a table built from a dictionary, or loaded from a file with no index column specified, it is a RangeIndex.
print(df.index) # RangeIndex(start=0, stop=5, step=1)
print(len(df.index)) # 5After filtering, the index keeps its original labels, so it can have gaps. A filtered table with len(df) == 3 may have index labels [0, 2, 4]. This matters because loc selects by label and iloc selects by position. If the two disagree, confirm which you are using by printing df.index.
dtypes: what type is each column?
df.dtypes returns a Series whose index is the column names and whose values are the dtypes.
print(df.dtypes)The output is:
name object
age float64
city object
salary int64
dtype: objectIn pandas 3, text columns display as str instead of object. The last line, dtype: object, describes the dtypes Series itself and is unrelated to your columns.
Because dtypes is a Series, you can use Series tools on it.
print(df.dtypes["age"]) # float64
print(df.dtypes.value_counts()) # how many columns of each dtype
print(df.dtypes[df.dtypes == "float64"].index.tolist()) # ['age']value_counts() on dtypes is useful for wide tables. A table with 300 columns is easier to understand as "180 float64, 100 object, 20 int64".
Common dtypes and what they mean
| dtype | Holds | Typical source |
|---|---|---|
| `int64` | Whole numbers, no missing values | Counts, IDs, salaries |
| `float64` | Decimal numbers, and whole numbers with missing values | Measurements, ages with gaps |
| `object` | Python objects, usually text (`str` in pandas 3) | Names, cities, mixed columns |
| `bool` | `True` or `False` | Flags |
| `datetime64[ns]` | Dates and times | Parsed timestamps |
| `category` | A fixed set of repeated values | Cities, status codes |
Why age is float64
The age column holds whole numbers, yet its dtype is float64. The classic NumPy-backed int64 dtype has no way to represent a missing value. NaN is a floating-point value, so pandas converts the whole column to float64 when one entry is missing.
This conversion happens silently. Values like 34 become 34.0, and the dtype is the only clue. To keep integers alongside missing values, use the nullable "Int64" dtype, with a capital I.
ages = df["age"].astype("Int64")
print(ages.dtype) # Int64
print(ages.tolist()) # [34, 28, <NA>, 45, 39]The object dtype is a catch-all
object means pandas stores each cell as a general Python object. For clean text columns this is fine, but object also appears when a column mixes types. The dtype alone does not tell you which case you have.
prices = pd.DataFrame({"price": ["10", "20", "n/a", "40"]})
print(prices.dtypes) # price objectThe prices look numeric, but the stray "n/a" forced the whole column to hold text. Arithmetic on this column would fail or concatenate strings instead of adding. dtypes is where you first see this, because you expected a number type and got object.
You can convert with pd.to_numeric. Setting errors="coerce" turns anything unparseable into NaN.
prices["price"] = pd.to_numeric(prices["price"], errors="coerce")
print(prices["price"].dtype) # float64
print(prices["price"].tolist()) # [10.0, 20.0, nan, 40.0]Selecting columns by dtype
When a table has many columns, select_dtypes filters by type. It uses the same names as dtypes.
numeric = df.select_dtypes(include="number")
print(numeric.columns.tolist()) # ['age', 'salary']
text = df.select_dtypes(include="object")
print(text.columns.tolist()) # ['name', 'city']This pairs with describe(include=...), which is covered later in the tutorial. Both use the same dtype names.
A quick-facts routine
For any new DataFrame, run these four lines before anything else:
print(df.shape)
print(df.columns.tolist())
print(df.dtypes)
print(df.index)Then compare the output against what you expected:
- Does the row count match the source, such as the file's line count minus the header?
- Are all expected columns present, with exact spelling and no stray spaces?
- Is each dtype plausible? Dates should not be
object, and IDs or amounts should not beobjectunless they are text. - Does the index look right, or do you need to set one?
Any "no" is a reason to stop and fix the loading step. Problems found here are cheaper to fix than the same problems found after a groupby or a plot.
Common mistakes
- Writing
df.shape()with parentheses, which raisesTypeError. - Reading
df.sizeas the row count. It is rows times columns. - Assuming a column is numeric because the values look numeric when printed. Check
dtypes. - Forgetting that one missing value turns an integer column into
float64. - Treating
objectas proof of clean text. It can hide mixed types. - Comparing dtypes to loose strings.
df.dtypes["age"] == "float64"works, but a typo in the string quietly returnsFalse.
Exercise
A DataFrame orders loads with orders.shape == (1200, 6). The quantity column should contain whole numbers, but orders.dtypes["quantity"] is object. Give two possible causes and name one function that converts the column while keeping track of bad entries.
Show answer
Possible causes: some entries contain non-numeric text such as "n/a", "unknown", or a number with a thousands separator like "1,200", or the file stores numbers in quotes with a stray text row mixed in. Either way pandas falls back to object. Use pd.to_numeric(orders["quantity"], errors="coerce"), which turns unparseable entries into NaN. Then count orders["quantity"].isna().sum() to see how many failed, and the column becomes float64 because of the NaN values. Use astype("Int64") afterwards if you want whole numbers with missing values.
Exercise
You run df.shape and get (5, 4). Write expressions that return (a) the number of rows, (b) the number of cells, and (c) a list of the column names, using no method on shape.
Show answer
(a) len(df), or df.shape[0]. (b) df.size, which is 5 * 4 = 20. (c) df.columns.tolist(). Note that shape is an attribute and a tuple, so df.shape[0] uses normal tuple indexing and df.shape() would raise a TypeError.