0

I have a dataframe constructed as follows:

df = pd.DataFrame({"taxon":["taxa1","taxa2","taxa3","taxa4","taxa5"],"rank":["genus","genus","family","species","species"]})

There are 3 different ranks in this example dataframe: genus, family and species. I want to extract the rows of df to create new dataframes for each of the ranks with the corresponding rows of that rank. The name of the new dataframe should be df_ followed by the name of the rank

So as output I want 3 dataframes df_genus, df_family, and df_species. Each of these contains the rows of that rank with the corresponding rows of the original df data frame.

I already tried several things, including:

ranks = ["genus","family","species"] 
for rank in ranks:
    "df_"+str(rank) = df.loc[df["rank"]==rank]

but this returns error: SyntaxError: can't assign to operator

How can I perform this operation?

3
  • Use a dict, with keys df_genus, df_family and df_species Commented Mar 12, 2020 at 11:26
  • Thank you for your answer. Could you please clarify? Commented Mar 12, 2020 at 11:28
  • 1
    Use d = {f'df_{k}': v for k, v in df.groupby('rank')} and access like d['df_genus'] etc. It's not a good idea to try and create variable names dynamically. see this post for more info Commented Mar 12, 2020 at 11:33

1 Answer 1

1

You can use globals() in order to create a dataframe inside a loop.

ranks = ["genus","family","species"] 
for rank in ranks:
    globals()["df_"+str(rank)] = df.loc[df["rank"]==rank]

Hope it helps :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.