Sub topic 3
DataFrame: a table of aligned columns
A DataFrame is pandas' two-dimensional table. This chapter covers how to build one, what its parts are, and why its columns stay aligned. It assumes you have read the chapters on Series and the Index. You should be comfortable with Python lists, dictionaries, and imports.
The working model
A DataFrame is an ordered collection of columns. Each column is a Series, and all the columns share one row Index. This model explains most DataFrame behavior:
- A row is a position in the shared Index, not a separate object.
- Each column has its own dtype, so one table can hold integers, floats, and strings side by side.
- Every column has the same length, because every column is labeled by the same Index.
The columns also have an Index of their own: the column labels. A DataFrame therefore has two axes, each with its own Index.
Building a DataFrame from a dictionary
The most common constructor takes a dictionary that maps column names to column values.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
"region": ["EU", "SA", "AS", "EU"],
})
print(df)
print(df.shape) # (4, 3)
print(df.index) # RangeIndex(start=0, stop=4, step=1)
print(df.columns) # Index(['city', 'pop_m', 'region'], dtype='object')
print(df.dtypes)Because you gave no index, pandas creates a RangeIndex of integers from 0. The dictionary keys become the column labels, in insertion order. df.dtypes returns a Series whose index is the column labels and whose values are the dtypes. The dtypes here are object for the two string columns and float64 for pop_m. Recent pandas versions may show str for string columns.
To use a meaningful row label instead, pass index=:
import pandas as pd
df = pd.DataFrame(
{"pop_m": [0.7, 10.7, 3.1], "region": ["EU", "SA", "AS"]},
index=["Oslo", "Lima", "Pune"],
)
print(df.loc["Lima", "pop_m"]) # 10.7Other ways to construct one
A list of dictionaries is common when your data comes from JSON or an API. Each dictionary is a row. Keys missing from a row become NaN:
import pandas as pd
rows = [
{"city": "Oslo", "pop_m": 0.7},
{"city": "Lima", "pop_m": 10.7, "region": "SA"},
]
df = pd.DataFrame(rows)
print(df)
# city pop_m region
# 0 Oslo 0.7 NaN
# 1 Lima 10.7 SAThe column set is the union of all keys. A list of lists works too, but it has no names, so you supply them with columns=:
import pandas as pd
df = pd.DataFrame(
[["Oslo", 0.7], ["Lima", 10.7]],
columns=["city", "pop_m"],
)
print(df)| Input | Each inner item is | Column names come from |
|---|---|---|
| dict of lists | a column | the dict keys |
| list of dicts | a row | the union of the keys |
| list of lists | a row | the `columns=` argument, or 0, 1, 2... |
| dict of Series | a column | the dict keys |
Building from Series: alignment happens at construction
When the values in the dictionary are Series, pandas aligns them on their Index labels. It does not align them by position. The row Index of the result is the union of all the Series indexes.
import pandas as pd
pop = pd.Series({"Oslo": 0.7, "Lima": 10.7, "Pune": 3.1})
area = pd.Series({"Oslo": 454, "Lima": 2672, "Rome": 1285})
df = pd.DataFrame({"pop_m": pop, "area_km2": area})
print(df)
print(df.dtypes)The result has four rows: Lima, Oslo, Pune, and Rome. Pune has no area, so it gets NaN. Rome has no population, so it also gets NaN. Because NaN is a float, area_km2 is converted from int64 to float64.
This is the same label-based matching you will see in arithmetic. It is the reason the title of this chapter says the columns are aligned.
Inspecting a DataFrame
Before you work with a table, check its structure. These are the attributes and methods you will use most:
df.shapereturns a tuple of(rows, columns).df.columnsanddf.indexreturn the two Index objects.df.dtypesreturns the dtype of each column.df.head(n)anddf.tail(n)return the first or lastnrows. The default is 5.df.info()prints the index range, each column's non-null count and dtype, and memory use.df.describe()returns summary statistics for numeric columns.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
"region": ["EU", "SA", "AS", "EU"],
})
df.info()
print(df.describe())info() prints its report directly and returns None. Do not wrap it in print().
Columns are Series
Selecting a single column with a label returns a Series. Selecting with a list of labels returns a DataFrame, even when the list has one item.
import pandas as pd
df = pd.DataFrame({
"city": ["Oslo", "Lima", "Pune", "Rome"],
"pop_m": [0.7, 10.7, 3.1, 2.8],
})
col = df["pop_m"]
print(type(col).__name__) # Series
print(col.name) # pop_m
print(col.index.equals(df.index)) # True
sub = df[["pop_m"]]
print(type(sub).__name__) # DataFrameThe Series keeps the DataFrame's row Index, and its name is the column label. This is why a column can be used in arithmetic with other columns of the same table without any alignment surprises. The shared Index guarantees the labels match.
Selection with loc and iloc is covered in a later chapter. Here you only need to know that df["name"] selects a column.
Common errors
Columns of different lengths
When you pass plain lists, every list must have the same length:
import pandas as pd
try:
pd.DataFrame({"a": [1, 2, 3], "b": [1, 2]})
except ValueError as e:
print(e) # All arrays must be of same lengthIf your values are Series, this error does not occur. Alignment fills the gaps with NaN instead. A length mismatch in plain lists is a data error, and pandas refuses to guess what you meant.
All scalar values
A dictionary of scalars has no length to infer, so pandas raises an error unless you supply an index:
import pandas as pd
try:
pd.DataFrame({"a": 1, "b": 2})
except ValueError as e:
print(e) # If using all scalar values, you must pass an index
row = pd.DataFrame({"a": 1, "b": 2}, index=[0])
print(row)Mixing one scalar with a list is allowed. The scalar is repeated for every row.
Attribute access that collides with a method
df.pop_m works only when the column name is a valid Python identifier and does not clash with an existing DataFrame attribute. A column named count, T, or index gives you the method or attribute, not your data. A column named "city name" cannot be reached this way at all. Use df["column"] for reading. Assigning with df.new_col = ... does not create a column.
Duplicate column labels
pandas allows duplicate column names. Then df["a"] returns a DataFrame with every column of that name, not a Series. Code that assumes a Series then fails in confusing ways. Check with df.columns.is_unique after combining data from several sources.
Row and column Index together
The two axes follow the same rules. Both are Index objects, and both can be named. Naming them helps when the table is printed or reshaped later:
import pandas as pd
df = pd.DataFrame(
{"pop_m": [0.7, 10.7], "region": ["EU", "SA"]},
index=pd.Index(["Oslo", "Lima"], name="city"),
)
print(df)
print(df.index.name) # city
print(df.columns.tolist()) # ['pop_m', 'region']You can also move a column into the row Index with set_index("city"), and move it back with reset_index(). Both return a new DataFrame and leave the original unchanged.
Exercise
You build pd.DataFrame({"x": pd.Series([1, 2], index=["a", "b"]), "y": pd.Series([3, 4], index=["b", "c"])}). How many rows does the result have, and what are the dtypes of x and y?
Show answer
Three rows, labeled a, b and c, because the row Index is the union of the two Series indexes. Row a has NaN in y, and row c has NaN in x. Both columns are float64, because NaN forces integer data to convert to float.
Exercise
A list of dictionaries is passed to pd.DataFrame. The first dictionary has keys id and name. The second has keys id and email. What columns does the result have, and what is in the email column for the first row?
Show answer
The columns are id, name, and email, the union of all keys. The first row's email value is NaN, because that dictionary has no email key.
Exercise
Why does pd.DataFrame({"a": 1, "b": 2}) raise an error, and name two ways to fix it?
Show answer
With only scalar values, pandas cannot tell how many rows to create. Fix it by passing an index, such as index=[0], or by making at least one value a list, such as {"a": [1], "b": [2]}.