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. This chapter covers the parts those methods report on: rows, columns, the index, and dtypes. Later chapters build on these terms.
Prerequisites
This chapter assumes you already have:
- Basic Python syntax: variables, lists, dictionaries, and function calls.
- pandas installed and imported as
pd, along with NumPy asnp. - Awareness that a DataFrame is a table of rows and labelled columns.
The parts of a DataFrame
A DataFrame is a two-dimensional table. It has four parts that matter when you inspect it.
- Rows are the records. In the example below, each row is one person.
- Columns are the named fields. Each column holds one kind of value, such as names or salaries.
- The index is the set of labels for the rows. By default it is the integers 0, 1, 2, and so on, but it can hold any labels.
- dtypes are the data types of the columns. Each column has exactly one dtype, such as
int64,float64, orobject.
Each column is a Series: a one-dimensional array of values that shares the DataFrame's index. A DataFrame is a collection of Series that line up on that index.
Building a small example
The tutorial uses one small DataFrame throughout. One age is missing on purpose, so you can see how pandas treats it.
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(df.index)
print(list(df.columns))
print(df.dtypes)Running this prints:
(5, 4)
RangeIndex(start=0, stop=5, step=1)
['name', 'age', 'city', 'salary']
name object
age float64
city object
salary int64
dtype: objectRead each line as follows:
shapeis a tuple of(rows, columns). Here there are 5 rows and 4 columns. The index is not counted as a column.indexis aRangeIndexfrom 0 up to, but not including, 5. This is the default when you do not supply labels.columnsholds the column labels, which you can turn into a list.dtypesreturns a Series that maps each column name to its dtype.
Why dtypes deserve attention
Two dtype facts in this example are easy to miss.
First, age is float64, even though the ages look like whole numbers. The reason is the missing value. np.nan is a floating-point value, and a standard NumPy-backed int64 column cannot hold it. When a column of integers contains a NaN, pandas converts the whole column to float64. A float column that you expected to be integers is often the first sign of missing data.
Second, name and city have the dtype object. This is the default for text in many pandas setups. It means each cell is a general Python object, here a string. Newer pandas versions can infer a dedicated string dtype instead, so the label you see may differ.
The dtype controls what you can do with a column. You can average a numeric column but not a text column. Methods like describe also choose their output based on dtype, which later chapters cover.
Common errors at this stage
- Treating the index as a column.
df.shapedoes not count the index, anddf["index"]raises aKeyError. To turn the index into a column, usedf.reset_index(). - Assuming the index starts at 1. The default index starts at 0. Row labels and row positions are different things, and you will see this when you select rows.
- Calling
df.shape().shapeis an attribute, not a method. Adding parentheses raisesTypeError: 'tuple' object is not callable. - Trusting how numbers look. A column that prints as
34.0is a float, not an integer. Checkdtypesrather than guessing from the display.
Exercise
Exercise
You load a DataFrame and see that a column of customer IDs, which you expected to hold whole numbers, has the dtype float64. What is the most likely cause, and which attribute do you use to check it?
Show answer
The column most likely contains at least one missing value (NaN). A NumPy-backed integer column cannot store NaN, so pandas converts the column to float64. Check it with df.dtypes, and count the missing values with df["column"].isna().sum().
Exercise
For a DataFrame with 200 rows and 6 columns and the default index, what does df.shape return, and what are the first and last index labels?
Show answer
It returns (200, 6). The default index is a RangeIndex from 0 to 199, so the first label is 0 and the last is 199.