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.

3
  • 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? Commented Mar 19, 2021 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: stackoverflow.com/questions/1373164/… Commented Mar 19, 2021 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. Commented Mar 19, 2021 at 14:52

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.