Dynamically Create Columns in Pandas Dataframe

Python

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".

 1|  multipliers = [2,3,4]
 2|  for i in multipliers:
 3|      df[f'times_{i}'] = df['A'] * i
 4|  
 5|  """
 6|  Expected Columns Names
 7|  ['A', 'B', 'times_2', 'times_3', 'times_4']
 8|  """
Did you find this snippet useful?

Sign up for free to to add this to your code library