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 new data frame using for loops and conditional statements

I am trying to create a for loop wherein a new dataframe is created based on a conditional statement of a column, but all I end up with is are only the column names without any values.

What I am doing now is the following:

for i in range(3):
    df_new = df[df['col'] == i]

but this does not seem to work.

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 :

Essentially with this for loop you are overwriting df and since the first and second conditions can’t be applied simultaneously, you will end with an empty dataframe.

You could create them dynamically within a dictionary, where the key is the name of the dataframe and the value the filtered dataframe. Try with:

dfs = {}
for i in range(3):
   dfs["df_"+str(i)] = df[df['col'] == i]

This will generate a dictionary that looks like the following structure:

{df_1:df[df['col']==1],
 df_2:df[df['col']==2]}

And you can access them via its key name dfs['df_1']

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