Pandas DataFrame - Iterate over Columns in the List


Pandas DataFrame - Iterate over Columns in the List

To iterate over the columns of a DataFrame in Pandas, iterate over the column names, and get the column from the DataFrame using the column name in each iteration.

In this tutorial, we will go through an example, with step by step explanation of how to iterate over the columns of a DataFrame using For loop.

Example

1. Iterate over columns of a DataFrame

In this example, we are given a DataFrame in df_input with three columns. We have iterate over the columns of this DataFrame using For loop.

Steps

  1. Given a DataFrame in df_input with three columns 'A', 'B', and 'C'.
df_input = pd.DataFrame({
    'A': [2, 4, 6],
    'B': [1, 3, 5],
    'C': [10, 20, 30]})
  1. Use a Python For loop to iterate over the column names of the DataFrame df_input, and get the column (Series object) using the column name from the DataFrame.
for column_name in df_input.columns:
    column = df_input[column_name]
  1. Convert this column (Series object) to a list. Please refer Pandas DataFrame - Convert column to list for a complete tutorial on this conversion.
column_as_list = column.tolist()
  1. You may print the column to output.
print(column_as_list)

Program

The complete program to iterate over the columns of a given DataFrame.

Python Program

import pandas as pd

# Take a DataFrame
df_input = pd.DataFrame({
    'A': [2, 4, 6],
    'B': [1, 3, 5],
    'C': [10, 20, 30]})

# Iterate over columns
for column_name in df_input.columns:
    # Get column (as series object)
    column = df_input[column_name]
    # Convert column to list
    column_as_list = column.tolist()
    # Print the column
    print(column_as_list)

Output

[2, 4, 6]
[1, 3, 5]
[10, 20, 30]

Summary

In this Pandas Tutorial, we learned how to iterate over the columns of a DataFrame using For loop, with examples.