Add New pandas DataFrame Columns in Loop in Python (Example Code)

In this article you’ll learn how to append new variables to a pandas DataFrame within a for loop in the Python programming language.

Setting up the Example

import pandas as pd                         # Import pandas library in Python
my_df = pd.DataFrame({'A':range(77, 88),    # Construct pandas DataFrame
                      'B':range(66, 77)})
print(my_df)
#      A   B
# 0   77  66
# 1   78  67
# 2   79  68
# 3   80  69
# 4   81  70
# 5   82  71
# 6   83  72
# 7   84  73
# 8   85  74
# 9   86  75
# 10  87  76

Example: Adding New Columns to a pandas DataFrame within a for Loop

for i in range(5):                          # Add new columns using for loop
    my_df[i] = i * 5
print(my_df)
#      A   B  0  1   2   3   4
# 0   77  66  0  5  10  15  20
# 1   78  67  0  5  10  15  20
# 2   79  68  0  5  10  15  20
# 3   80  69  0  5  10  15  20
# 4   81  70  0  5  10  15  20
# 5   82  71  0  5  10  15  20
# 6   83  72  0  5  10  15  20
# 7   84  73  0  5  10  15  20
# 8   85  74  0  5  10  15  20
# 9   86  75  0  5  10  15  20
# 10  87  76  0  5  10  15  20

Further Resources & Related Tutorials

You may find some additional Python tutorials on topics such as text elements, descriptive statistics, and naming data below:

Leave a Reply

Your email address will not be published.

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