1 Upvote

Dynamically Create Columns in Pandas Dataframe

Python
Data Preprocessing

In this example both the values in the columns and the column names are created dynamically.

Here we dynamically create three columns that multiply the column A in our dataframe by each of the numbers in the list "multipliers".

multipliers = [2,3,4]
for i in multipliers:
    df[f'times_{i}'] = df['A'] * i

df.columns

>> Index(['A', 'B', 'times_2', 'times_3', 'times_4'], dtype='object')

By detro - Last Updated March 29, 2022, 7:34 p.m.

Did you find this snippet useful?

Sign up to bookmark this in your snippet library

COMMENTS
RELATED SNIPPETS
Pivoting Pandas Dataframes
Python
Data Preprocessing

Pandas

3
2
Top Contributors
103
100