0

I'm trying to create a series of variables based on an existing df column. Example :

import pandas as pd

dates = {'expiries': ['10','11','13','14']}
expiries = pd.DataFrame(dates)
expiries 

I then want to create a new variable (var1 through var4) giving it the value from each row. I know I can get it by going:

var1 = expiries['expiries'].iloc[0]
var2 = expiries['expiries'].iloc[1]
var3 = expiries['expiries'].iloc[2]
var4 = expiries['expiries'].iloc[3]

but in reality my df is a variable length and I need a variable per row not a pre determined (hardcoded) number of variables.

breaker7
  • 113
  • 8
  • 2
    The question is why? If you don't know the number of variables, how do you type them? Are you looking into some sort of `for` loop? – Quang Hoang Mar 19 '21 at 14:33
  • 1
    you can store in a dict : `expiries['expiries'].to_dict()` and refer the keys later if really required, since creating variables from a loop isnt a great idea. ref: https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables – anky Mar 19 '21 at 14:43
  • I'm using the variables to create columns in a new df. I then reference that df with some visualisations. An initial product selection determines the number of expiries. Sometimes 15 sometimes 20. If I preset the variables to 20, when my product only has 15 the visualisations dont run as they are missing columns. Appreciate the advice that its anti code logic. – breaker7 Mar 19 '21 at 14:52

2 Answers2

1

store them in the dict:

var_dict = {}
for i in range(expires.shape[0]):
    var_dict['var' + str(i+1)] = expiries['expiries'].iloc[i]

it is against coding logic that you have unknown number of variables

Artyom Akselrod
  • 946
  • 6
  • 14
1

you could use exec

for row in expiries.itertuples():
    idx, value = row
    exec(f'var{idx+1} = {value}')

print(var1, var2, var3, var4)
>>>
10 11 13 14
Miguel Trejo
  • 5,913
  • 5
  • 24
  • 49