Sub topic 1
What you are selecting from: index, columns, and values
This chapter describes the structure of a pandas DataFrame. Every selection method in the later chapters, such as brackets, .loc, .iloc, boolean masks, and query, works on these parts. If you can name them and predict what each one holds, the later rules are easier to learn.
Prerequisites
This chapter assumes you have the following:
- Basic Python syntax, including lists, dictionaries, and slices.
- pandas installed and imported as
pd. - Some familiarity with creating a DataFrame from a dictionary.
You do not need any prior knowledge of selection. This chapter is the starting point for it.
The three parts of a DataFrame
A DataFrame is a two-dimensional table. It has three parts that you can inspect separately:
- The index holds the row labels. It has one entry per row.
- The columns hold the column labels. It has one entry per column.
- The values are the data in the cells.
Every cell sits at the crossing of one row label and one column label. When you select data, you describe a region of this grid by naming labels, giving positions, or computing a True/False answer for each row.
The following diagram shows how these parts relate.
Building the example DataFrame
The chapters in this tutorial reuse one small DataFrame. It describes five cities. The index uses the strings "a" to "e" instead of the default integers. This is deliberate. With a string index, labels and positions look different, and you can always tell which one a piece of code is using.
import pandas as pd
df = pd.DataFrame(
{
"city": ["Oslo", "Lima", "Pune", "Cairo", "Quito"],
"country": ["Norway", "Peru", "India", "Egypt", "Ecuador"],
"population_k": [709, 10092, 3124, 10230, 2800],
"continent": ["Europe", "South America", "Asia", "Africa", "South America"],
},
index=["a", "b", "c", "d", "e"],
)
print(df.index)
print(df.columns)
print(df.dtypes)Printing df itself shows the whole table:
| Row | city | country | population_k | continent |
|---|---|---|---|---|
| a | Oslo | Norway | 709 | Europe |
| b | Lima | Peru | 10092 | South America |
| c | Pune | India | 3124 | Asia |
| d | Cairo | Egypt | 10230 | Africa |
| e | Quito | Ecuador | 2800 | South America |
The column population_k holds population in thousands. The _k suffix is only a naming convention. pandas does not interpret it.
Reading the index
The line print(df.index) shows an Index object. For this DataFrame it looks like this:
Index(['a', 'b', 'c', 'd', 'e'], dtype='object')Points to know about the index:
- Index labels do not have to be strings. They can be integers, dates, or other hashable values.
- If you do not pass
index=, pandas creates aRangeIndexof integers starting at 0. - Index labels do not have to be unique. A lookup on a duplicated label returns several rows. This is legal, but it makes assignment and joins harder to reason about.
- The index is not a column. It does not appear in
df.columns, and it is not counted when you ask for the number of columns.
Every row also has a position, which is its integer offset from the top, starting at 0. Position and label are two separate addresses for the same row. In df, the row labeled "b" is at position 1. When the index is the default RangeIndex, label and position happen to be equal, which hides the difference. That is why this tutorial uses letters.
Reading the columns
print(df.columns) shows another Index object, this time holding the column names:
Index(['city', 'country', 'population_k', 'continent'], dtype='object')Columns are also an Index, so they share the same properties. Each column has a label and a position. Column labels are usually strings, but integers are allowed. Selecting df[0] on a DataFrame with string columns raises a KeyError, because 0 is treated as a label and no column has that label.
Reading the dtypes
print(df.dtypes) shows one data type per column. In recent pandas versions, the output is similar to this:
city object
country object
population_k int64
continent object
dtype: objectThe exact string for text columns depends on your pandas version and settings. Older versions show object. Newer versions may show str or string when the string dtype is enabled. The numeric column is int64 in either case.
The key fact is that each column has its own dtype. A DataFrame is not one uniform grid of numbers. It is a set of columns, and each column is a typed array. This has three consequences for selection:
- A numeric column supports comparisons such as
> 3000and.between(...). - A text column supports string methods through the
.straccessor. - You can pick columns by dtype, as a later chapter shows with
select_dtypes.
The values and the underlying array
The values are the cell contents. You can look at them as a NumPy array:
print(df.to_numpy())Because the columns have mixed dtypes, NumPy cannot store them as numbers. It falls back to a single array of Python objects, and the integers become generic objects. This is a lossy view. For this reason, treat df.to_numpy() as a way to export data, not as a way to select it. Selection is done on the DataFrame itself, so the labels and dtypes stay attached to the data.
What a selection returns
The shape of what you get back depends on how many labels you ask for. This rule recurs in every later chapter:
| You ask for | You get |
|---|---|
| One column label, such as `df["city"]` | A `Series` |
| A list of column labels, such as `df[["city"]]` | A `DataFrame` |
| One row label, such as `df.loc["b"]` | A `Series` |
| A list or slice of row labels | A `DataFrame` |
| One row label and one column label, via `.loc` | A single scalar value |
A Series is a one-dimensional labeled array. It has an index, values, and a name, but no columns. When you select one column, the Series carries the DataFrame's row index with it, and its name is the column label. When you select one row, the Series is indexed by the column labels, and its name is the row label.
Note that a single-element list still gives a DataFrame. df["city"] is a Series and df[["city"]] is a one-column DataFrame. Code that expects one or the other will fail in different ways, so check which you have when a method behaves unexpectedly.
Inspecting a DataFrame before selecting
Before you write a filter, it helps to look at the structure. These attributes cost almost nothing to call:
print(df.shape) # (5, 4): five rows, four columns
print(list(df.index)) # ['a', 'b', 'c', 'd', 'e']
print(list(df.columns)) # ['city', 'country', 'population_k', 'continent']
print(df.index.is_unique)
print(df.loc["b"]) # one row, as a Series
print(type(df.loc["b"]))df.shape returns a tuple of (rows, columns). The index is not counted as a column.
When you select a single row with df.loc["b"], pandas must put a mix of text and numbers into one Series. The resulting Series has dtype object, because a single Series holds one dtype. This is a common surprise. Selecting a row from a mixed-dtype DataFrame can change numbers into objects. Selecting a column keeps the column's dtype.
Common errors at this level
These mistakes come from misreading the structure.
- Treating the index as a column.
df["a"]fails with aKeyError, because"a"is a row label, not a column label. Usedf.loc["a"]for a row. - Confusing label and position. On a default integer index,
df.loc[1]anddf.iloc[1]give the same row, so the mix-up goes unnoticed. After a filter or sort, the labels no longer match the positions, and the code breaks or silently selects the wrong row. - Assuming
df[x]always returns a DataFrame. It returns a Series for a single label. Use a list when you need a DataFrame. - Reading dtypes from the printed table. A column of numbers stored as text prints like a numeric column. Check
df.dtypesbefore you apply a numeric comparison. - Assuming labels are unique. Call
df.index.is_uniqueif you plan to look up one label and expect one row.
How this maps to the rest of the tutorial
Each later chapter works on one part of the structure:
- Column selection with brackets works on the columns.
.locselects by labels from the index and columns, and.ilocselects by positions.- Boolean masks compute one True/False value per row, aligned to the index.
isin,between, and.strmethods depend on the column dtype.select_dtypesandfilterchoose among the columns.
The alignment point matters. A boolean mask is a Series whose index matches the DataFrame's index. pandas uses the labels to line them up, not the positions. This is one reason it is worth understanding the index now.
Exercise
Using the df from this chapter, what type does df["population_k"] return, what is its name, and what does its index contain? Then say what changes if you write df[["population_k"]] instead.
Show answer
df["population_k"] returns a Series with dtype int64. Its name is "populationk", and its index is the DataFrame's row index, ['a', 'b', 'c', 'd', 'e']. Writing `df[["populationk"]]` returns a DataFrame with one column, because a list of labels always gives a DataFrame. It still has the same row index and one column labeled "population_k".
Exercise
A DataFrame has the default integer index. You sort it with sorted_df = df.sort_values("population_k"). The row that was at position 3 is now at position 0. Without running any code, say what sorted_df.index[0] is and why .loc[0] and .iloc[0] may now return different rows.
Show answer
sorted_df.index[0] is 3, because sorting reorders the rows but keeps each row's original label. The row now at position 0 still has the label 3. .loc[0] looks for the label 0, which is wherever the original first row ended up. .iloc[0] returns whatever row is now first. These are different rows unless the original first row is also the smallest.
Exercise
Why does df.loc["b"] return a Series with dtype object for the example DataFrame, while df["population_k"] returns a Series with dtype int64?
Show answer
A Series holds a single dtype. A column contains values of one type, so its dtype is kept. A row mixes text values and an integer, so pandas stores them all as generic Python objects, and the integer loses its numeric dtype.