Add grouped by dataframe into multiple files?

Question:

I have a piece of code that I need to push into multiple HTML files and create a PDF withe them, I do not have any struggle with the PDF part of this, however I have an issue when creating the HTML files and pushing the data into the files. This is my code:

new_dataframe = dict(tuple(df.groupby(['Course'])))
for new_df in new_dataframe.values():
    print(new_df)
    new_index = new_df.index[-1]
    html_df = new_df.iloc[:new_index]
for i in range(len(unique_courses) - 1):
    if unique_courses[i] != unique_courses[i + 1]:
        file = open('example %s.html' % i, 'w')
        file.write(new_df.to_html())

the file.write(new_df.to_html()) is what I am struggling on, as it is only taking the last dataframe that has been grouped by, and is turning that into HTML and then pushing the same data to all 4 files it has created instead of reading all 4 dataframes that I have and writing them to each file.
Any help is appreciated, thanks.

Asked By: Jack Jennings

||

Answers:

If I understand correctly, something like this should work.

new_dataframe = dict(tuple(df.groupby(['Course'])))
for course, new_df in new_dataframe.items():
    with open(f'example_{course}.html', 'w') as outfile:
        outfile.write(new_df.to_html())
Answered By: fsimonjetz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.