i want to separate data frame based on marks and download it then

Viewed 40

This is my data frame:

     Name  Age    Stream  Percentage
0      A   21      Math          88
1      B   19  Commerce          92
2      C   20      Arts          95
3      D   18   Biology          70
0      E   21      Math          88
1      F   19  Commerce          92
2      G   20      Arts          95
3      H   18   Biology          70

I want to download different excel file for each subject in one loop so basically, I should get 4 excel files for each subject

i tried this but didn't work:

n=0
for subjects in df.stream:
  df.to_excel("sub"+ str(n)+".xlsx") 
  n+=1
1 Answers

I think groupby is helpful here. and you can use enumerate to keep track of the index.

for i, (group, group_df) in enumerate(df.groupby('stream')):
    group_df.to_excel('sub{}.xlsx'.format(i))
    # Alternatively, to name the file based on the stream...
    group_df.to_excel('sub{}.xlsx'.format(group))

group is going to be the name of the stream.

group_df is going to be a sub-dataframe containing all the data in that group.

Related