HOWTO · Pandas

How to Iterate Through Columns of a Pandas DataFrame

This tutorial demonstrates how to iterate through columns of a dataframe

On this page

To iterate over a Pandas DataFrame’s columns, loop over the DataFrame to receive each column label, then use df[column] to select that column as a Series. Use DataFrame.items() when you want the label and Series together, or enumerate() when you also need each column’s position.

Iterate over columns with a for loop and df[column]

A DataFrame loop visits its column labels. In each pass, df[column] selects the Series associated with that label. This example prints each column label followed by its values as a Python list:

import pandas as pd

df = pd.DataFrame(
    {"name": ["Ada", "Lin"], "score": [9, 8]}
)

for column in df:
    print(column, df[column].tolist())
name ['Ada', 'Lin']
score [9, 8]

The loop variable is a label such as name or score; it is not a row number. The selected Series retains the DataFrame’s row index. Convert to a list with .tolist() only when a list is useful for the next step; .values instead exposes an array-like representation.

Iterate over column labels and Series with DataFrame.items()

DataFrame.items() yields each column label paired with its Series. Unpack that pair to work with both values directly. This example prints each label and its Series values:

import pandas as pd

df = pd.DataFrame(
    {"name": ["Ada", "Lin"], "score": [9, 8]}
)

for column_label, series in df.items():
    print(column_label, series.tolist())
name ['Ada', 'Lin']
score [9, 8]

Choose this pattern when your operation needs the label and the corresponding Series in the same loop. For instance, you can apply a separate formatting or summary step to each column. If a calculation can be expressed across the DataFrame at once, a vectorized Pandas operation may be clearer than handling columns one by one.

Get each column’s position and label with enumerate()

Wrap df.columns in Python’s built-in enumerate() to pair each label with its zero-based position in the column sequence. The example prints each column’s zero-based position followed by its label:

import pandas as pd

df = pd.DataFrame(
    {"name": ["Ada", "Lin"], "score": [9, 8]}
)

for position, column_label in enumerate(df.columns):
    print(position, column_label)
0 name
1 score

Here, position is 0 for the first column, 1 for the second, and so on. It is distinct from a row index label, which identifies rows and can have values that are not consecutive integers. Use this form when another operation requires a column’s order as well as its label; use the basic loop or DataFrame.items() when the position is unnecessary.