Is there any way of using for loop iterator in variable name?

I am looking for a way to dynamically use multiple dataframes in a for loop. Any ideas?

I generated 24 dataframes like this ("hour" is 0-23):

N = 24

for i in range(int(N)):
    exec("df_hour{} = df_m_a_meaned[df_m_a_meaned['hour']=={}]".format(i, i))`

Now I want to use them in a for-loop to generate a plot, I tried this but it obviously isn’t working:

fig = go.Figure(data=[go.Box(
    x="df_hour{}['hour']".format(i),
    y="df_hour{}['priceNum']".format(i), 
    ) for i in range(int(N))])

>Solution :

don’t EVER use exec to generate variables in your normal code, it will only make things harder see Why should exec() and eval() be avoided?, if you want to generate dynamically named variables use a dictionary instead.

my_dataframes = {}
for i in range(int(N)):
    my_dataframes[i] = df_m_a_meaned[df_m_a_meaned['hour']==i]

fig = go.Figure(data=[go.Box(
    x=my_dataframes[i]['hour'],
    y=my_dataframes[i]['priceNum'], 
    ) for i in range(int(N))])

Leave a Reply