Sub topic 3
Quick facts: shape, columns, and dtypes
This chapter assumes you know basic Python syntax, have pandas installed and imported as pd, and know that a DataFrame is a table of rows and labelled columns. Here you will read a DataFrame's size, labels, and column types without printing any data.
Attributes, not methods
head() and info() are methods, so they need parentheses. shape, columns, index, and dtypes are attributes. They are values stored on the DataFrame, so you read them without parentheses.
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.shape)
print(list(df.columns))
print(df.index)
print(df.dtypes)The output is:
(5, 4)
['name', 'age', 'city', 'salary']
RangeIndex(start=0, stop=5, step=1)
name object
age float64
city object
salary int64
dtype: objectShape
df.shape is a tuple of (rows, columns). Here it is (5, 4). The index and column labels are not counted as data, so a table with five rows and four columns has that shape.
Because it is a plain tuple, you can unpack it or index it:
n_rows, n_cols = df.shape
print(n_rows)
print(len(df))Both lines print 5. len(df) also returns the number of rows.
Check shape first on any new dataset. It tells you whether head() will show the whole table or a small part of it. It also lets you confirm a file loaded as expected. A file with 12 columns that loads with 1 usually means the wrong delimiter was used.
Columns and index
df.columns holds the column labels. Wrapping it in list() gives a clean printout you can copy into code. Check the labels for stray spaces or inconsistent capitalization, such as "City " versus "city". These cause KeyError later.
df.index holds the row labels. RangeIndex(start=0, stop=5, step=1) means the labels are the default integers 0 to 4. A different index, such as dates or IDs, tells you rows are looked up by those labels.
Dtypes
df.dtypes returns a Series. Its index is the column names, and its values are the data type of each column. Common dtypes:
| dtype | Meaning |
|---|---|
| `int64` | Whole numbers, with no missing values |
| `float64` | Decimal numbers, or whole numbers with missing values |
| `object` | Text, or a mix of Python objects (newer pandas versions may show `str` for text) |
| `bool` | True or False |
| `datetime64[ns]` | Dates and times |
The age column is float64 even though every age is a whole number. NumPy's nan is a floating-point value, so one missing entry makes pandas store the whole column as floats. A float dtype on a column that should be whole numbers often means some values are missing.
Using dtypes to catch problems
Compare each dtype with what you expect. Two mismatches are common:
- A column of numbers shows
object. Some entries are probably text, such as"N/A"or"$1,200", so arithmetic on the column will fail or behave unexpectedly. - A column of dates shows
object. The values are plain strings, so date operations won't work until you convert them.
You can also select columns by dtype with select_dtypes:
numeric_cols = df.select_dtypes(include="number").columns
print(list(numeric_cols))This prints ['age', 'salary'].
Common errors
df.shape()This raises TypeError: 'tuple' object is not callable. shape is already a tuple, so adding parentheses tries to call it. The same mistake with df.dtypes() also fails, because dtypes returns a Series.
The reverse mistake is writing df.head without parentheses. That doesn't fail. It prints a description of the method object instead of the first rows.
Exercise
A column called "price" shows dtype object, but you expected decimal numbers. What does this suggest, and which attribute showed it to you?
Show answer
Some entries in the column are not numbers, for example text such as "N/A" or a value with a currency symbol. The dtypes attribute (df.dtypes) showed the object dtype. Look at the values in that column before converting it to a numeric type.
Exercise
What does df.shape return for a DataFrame with 200 rows and 7 columns, and why is df.shape() an error?
Show answer
It returns the tuple (200, 7). It is an error because shape is an attribute holding a tuple, not a method, so calling it with parentheses raises TypeError: 'tuple' object is not callable.