Loop & Iterate Through pandas DataFrame Columns in Python (Example Code)

This post explains how to loop through the columns of a pandas DataFrame in Python programming.

Constructing Example Data

import pandas as pd                        # Import pandas
my_df = pd.DataFrame({'A':range(8, 14),    # Construct pandas DataFrame
                      'B':['x', 'y', 'y', 'y', 'x', 'x'],
                      'C':range(15, 9, - 1)})
print(my_df)
#     A  B   C
# 0   8  x  15
# 1   9  y  14
# 2  10  y  13
# 3  11  y  12
# 4  12  x  11
# 5  13  x  10

Example: Print Columns of pandas DataFrame Using for Loop

for column in my_df:                       # Run for loop over columns
    print(my_df[column])
# 0     8
# 1     9
# 2    10
# 3    11
# 4    12
# 5    13
# Name: A, dtype: int64
# 0    x
# 1    y
# 2    y
# 3    y
# 4    x
# 5    x
# Name: B, dtype: object
# 0    15
# 1    14
# 2    13
# 3    12
# 4    11
# 5    10
# Name: C, dtype: int64

Related Articles

Please find some related Python tutorials on topics such as descriptive statistics, numeric values, and naming data below:

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top