Sub topic 3
DataFrame: a table of aligned columns
This chapter assumes you can write basic Python (lists, dictionaries, imports) and that you have met the Series and the Index in the earlier chapters. Here you will see how a DataFrame combines them into a table.
The working model
A DataFrame is a set of columns. Each column is a Series, and all the columns share one row Index. The DataFrame also has a column Index, which holds the column names. Because every column uses the same row labels, a value in one column lines up with the values in the other columns on the same row.
Building a DataFrame
The most common way to build one from Python data is a dictionary. Each key becomes a column name, and each value is a list or Series that becomes the column.
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): four rows, three columns
print(df.columns.tolist()) # ['city', 'pop_m', 'region']
print(df.index) # RangeIndex(start=0, stop=4, step=1)No row index was given, so pandas created a RangeIndex of the integers 0 to 3. You can pass index=[...] to use your own labels.
Columns are Series
Selecting one column with df["pop_m"] returns a Series. It keeps the DataFrame's row Index and takes the column name as its name.
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[["city", "pop_m"]]
print(type(sub).__name__) # DataFramePassing a list of names, as in df[["city", "pop_m"]], returns a DataFrame instead. The double brackets are a list inside the selection brackets.
Inspecting a DataFrame
Three calls give you a quick picture of a table:
| Call | What it shows |
|---|---|
| `df.head(n)` | The first `n` rows (5 by default) |
| `df.info()` | Column names, dtypes, non-null counts, memory use |
| `df.describe()` | Count, mean, spread and quartiles of numeric columns |
Aligned columns and mixed dtypes
Each column has its own dtype. In the example above, city holds text (dtype object or str, depending on your pandas version) and pop_m holds float64. Within one column the dtype is uniform. Across columns it can differ. This is the main difference from a plain NumPy array, which has one dtype for the whole array.
When you build a DataFrame from Series, pandas aligns them on their labels, not on position.
import pandas as pd
a = pd.Series([1, 2, 3], index=["x", "y", "z"])
b = pd.Series([10, 20, 30], index=["y", "z", "w"])
print(pd.DataFrame({"a": a, "b": b}))The result has four rows (x, y, z, w). Where a label is missing from one Series, that cell becomes NaN. Alignment is covered in detail in a later chapter.
Common errors
- Columns of unequal length.
pd.DataFrame({"a": [1, 2], "b": [1, 2, 3]})raises aValueError, because plain lists are matched by position and must have the same length. - Confusing one and two brackets.
df["city"]gives a Series.df[["city"]]gives a one-column DataFrame. - Expecting position-based matching from Series. Series are matched by label, so two Series with different indexes produce
NaNcells.
Exercise
Given df with columns city, popm and region, what is the difference between `df["popm"] and df[["pop_m"]]`, and why do both have the same row labels?
Show answer
df["pop_m"] returns a Series named popm. `df[["popm"]]` returns a DataFrame with one column. Both keep the same row labels because every column of a DataFrame shares the DataFrame's row Index.