-1

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))])
wolliumm
  • 31
  • 3
  • Have a list or dictionary of the dataframes you want to iterate over? Dynamically creating variable names at run time is usually a bad idea, one that makes code less readable. – John Coleman Nov 09 '22 at 12:17

1 Answers1

2

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))])
Ahmed AEK
  • 8,584
  • 2
  • 7
  • 23
  • Thank you! Can you explain why using exec makes things harder? I am quite new to python. – wolliumm Nov 09 '22 at 12:19
  • @wolliumm read the following answers https://stackoverflow.com/questions/1933451/why-should-exec-and-eval-be-avoided – Ahmed AEK Nov 09 '22 at 12:20
  • 2
    @wolliumm Just let me say this: I work with Python since nearly 20 years and I never needed `exec`. – Matthias Nov 09 '22 at 12:44