Sub topic 1
What You Are Selecting from: Index, Columns, and Values
Prerequisites
Assume basic Python syntax, including lists, dictionaries, and slices. You should also know how to create a DataFrame and import pandas as pd.
A pandas DataFrame is a table with three important parts:
- The index identifies rows. It contains labels such as
"a"or"b". - The columns identify fields such as
"city"or"population_k". - The values are the data stored where an index label and column label meet.
import pandas as pd
df = pd.DataFrame(
{
"city": ["Oslo", "Lima", "Pune"],
"country": ["Norway", "Peru", "India"],
"population_k": [709, 10092, 3124],
},
index=["a", "b", "c"],
)
print(df.index)
print(df.columns)
print(df.dtypes)Selecting One or More Columns
Use brackets with a column label. Selecting one column returns a Series, which is pandas’ one-dimensional labeled data structure. Selecting a list of labels returns another DataFrame.
cities = df["city"]
summary = df[["city", "population_k"]]
print(type(cities))
print(summary)A common error is using df["city", "country"]. That expression requests one tuple-shaped label. Use a list inside the brackets instead: df[["city", "country"]].
Labels versus Positions
Pandas supports two ways to identify data:
- Labels are explicit names in the index or columns.
- Positions are zero-based integer locations, where the first row or column is position
0.
The index labels do not have to be numbers or start at zero. Use .loc for labels and .iloc for positions.
Selecting Rows and Columns with `.loc`
.loc accepts a row label, row-label slice, and optional column label or list of labels. Label slices include both endpoints.
print(df.loc["a":"b", ["city", "population_k"]])This selects rows "a" and "b". The equivalent positional selection would be:
print(df.iloc[0:2, [0, 2]])Here, the ending position 2 is excluded, as it is in ordinary Python slicing.
Exercise
Which expression selects rows labeled "b" and "c", plus the "city" column?
Show answer
df.loc["b":"c", "city"]