0

I'm trying to write on an excel the following:

<table>
  <tr>
    <td>user</td><td>4</td><td>Method</td><td>method 1</td>
  </tr>  
  <tr>
    <td></td><td>title</td><td>note</td>
  </tr>
  <tr>
    <td></td><td>Hangover</td><td>7</td>
  </tr>
  <tr>
    <td></td><td>...</td><td>...</td>
  </tr>
  <tr>
    <td>user</td><td>4</td><td>Method</td><td>method 2</td>
  </tr>
  <tr>
    <td></td><td>title</td><td>note</td>
  </tr>
  <tr>
    <td></td><td>Lord of the ring</td><td>9</td>
  </tr>
  <tr>
    <td></td><td>...</td><td>...</td>
  </tr>
</table>

So I did the following code:

def get_users_recommandation(users, score_mpm_user, score_mpm_unique_user):
   writer = pd.ExcelWriter('recommendation.xlsx', engine='xlsxwriter')
   for user in users:
       label = pd.DataFrame({'user' : [user], 'method' : "mpm unique"})
       label.to_excel(writer, sheet_name='Sheet1')
       recommendation = get_recommandation(score_mpm_unique_user, user)
       df_recommendation = get_data_frame_from_recommendation(recommendation)
       df_recommendation.to_excel(writer, sheet_name='Sheet1')
       label = pd.DataFrame({'user' : [user], 'method' : "mpms"})
       label.to_excel(writer, sheet_name='Sheet1')
       recommendation = get_recommandation(score_mpm_user, user)
       df_recommendation = get_data_frame_from_recommendation(recommendation)
       df_recommendation.to_excel(writer, sheet_name='Sheet1')

But the problem when I'm doing so is that I overwrite the previous content and the result is only the last write I did. I'm new to pandas and I don't really know how to do. Should I build an entire data frame from the 4 previous one is there some other method to append data frame at the end of the previous one.

mel
  • 2,730
  • 8
  • 35
  • 70

2 Answers2

1

Hope it helps you you can append all the dataframes and then write it to excel:
data=label.append(df_recommendation)
similarly for the next two dataframes.

shivsn
  • 7,680
  • 1
  • 26
  • 33
1

You can use openpyxl to modify existing excel files with pandas.

look on this example: https://stackoverflow.com/a/20221655/590335

Community
  • 1
  • 1
Ophir Yoktan
  • 8,149
  • 7
  • 58
  • 106