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

Question:

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))])
Asked By: wolliumm

||

Answers:

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))])
Answered By: Ahmed AEK
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.