Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading