Python Forum
dynamically create variables' names in python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
dynamically create variables' names in python
#5
Thanks for your recommendations guys.
I created a list in the below way:

dfs = []
for df_gen in np.arange (min_range_v, max_range_v):
    df_name = 'df_'+str(int(df_gen+min_year))
    dfs.append(df_name)
dfs
it returns this:
Output:
['df_2001', 'df_2002', 'df_2003', 'df_2004', 'df_2005', 'df_2006', 'df_2007', 'df_2008', 'df_2009', 'df_2010', 'df_2011', 'df_2012', 'df_2013', 'df_2014', 'df_2015', 'df_2016', 'df_2017', 'df_2018', 'df_2019']
In between the above an the below there is some code that populate the dataframe df.
The above list contains exactly the dataframes names i want to create BUT, when i try to access them i can't use the names (for example df_2001) instead i must use dfs[0] but that create an issue as all the info that i add at each for loop, it is mixed with the previous updated df.
This is what i do after the above:
In order to insert the new df info at each loop, i created a new df and i copy the existing df at each loop, then reset it at the beginning of the loop till it ends the loop and add it to the below:

some dynamically generated code to populate the dataframe df.
then at the end of the loop (just before it ends):

dfs[i] = df.copy()
but in the above way i can't obtains several different dataframes, and additionally if i try to call

df_2001
i get the below:

Error:
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-27-81242f59523c> in <module> ----> 1 df_2001 NameError: name 'df_2001' is not defined
i also tried to do the below:
str(dfs[0])
but still it doesnt create a variable/dataframe name...
i am really struggling with it...

If i call
dfs[0]
i get the dataframe but can't use the name df_2001
and if i call
dfs[0].shape
i get the below (which is way larger than what the dfs[0] is supposed to be as it should contain MAX 365 days (rows).
but what i get is this:
Output:
(4784, 62)
and the same output happen for every other dfs[i].

How can i sort it out to make sure i can access exactly the different dfs[i] like if they were independent dataframes?
potentially how can i access them with the name df_2001 etc?
Many thanks in advance for your great help,
Marco.
Reply


Messages In This Thread
RE: dynamically create variables' names in python - by marco_ita - Sep-23-2019, 04:47 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020