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

How to create a dataframe with every iteration of a for loop

I have the following code.


dict_of_df={}
for i in range(100):
    get_data = [data for data in cur]
    df = pd.DataFrame(get_data)
    dict_of_df[f"df_{i}"] = df

This gives me a dictionary of 100 dataframes. However, I need to assign each dataframe to a variable for it to be recognised and imported into another program (Microsoft Power BI). Is there a way I can assign each dataframe in the dictionary to a unique variable? Based on what I’ve read here How to create a new dataframe with every iteration of for loop in Python , a dictionary is the only way of storing the dataframe from each iteration but I need a way to extract it to my workspace.

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

>Solution :

Use globals() to create your variables dynamically. Use with caution, it’s not really a good practice but it should work:

for i in range(100):
    get_data = [data for data in cur]
    df = pd.DataFrame(get_data)
    globals()[f"df_{i}"] = df  # <- replace your dict by globals()
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