简体   繁体   中英

Python: how can I export dataframe to existing Excel sheet but not creating a new sheet

I would like to export my dataframes to specified columns in existing Excel sheet in Python and I have tried different ways but they don't work. I have already exported df1 to an excel sheet called "IR delta" and now I would like to export df2 to the same sheet as df1 after running some codes to generate df2 . However, excel sheet "IR delta1" is created instead of exporting the same sheet "IR delta". Can anyone please help? Many thanks!

df1

  Qualifier                   Currency Risk Group  Delta Concentration threshold (USD/bp)   CR
0       AUD  Regular volatility, less well-traded                                41000000  1.0
1       CHF  Regular volatility, less well-traded                                41000000  1.0
2       CNY                       High volatility                                31000000  1.0
3       EUR       Regular volatility, well-traded                               220000000  1.0

df2

   Qualifier      Curve Tenor        RiskType  Risk Weight   CR            WS
0        AUD    Libor3m    1m    Risk_IRCurve          107    1  2.140000e+08
1        AUD    Libor3m    2y    Risk_IRCurve           53    1 -1.060000e+08
2        AUD    Libor3m    6m    Risk_IRCurve           71    1  2.130000e+08
3        CHF    Libor6m   15y    Risk_IRCurve           50    1 -2.000000e+08
4        CHF    Libor6m   20y    Risk_IRCurve           54    1  5.400000e+08
5        CHF    Libor6m   30y    Risk_IRCurve           63    1  7.560000e+08

Please see my code below:

writer = pd.ExcelWriter(Results, engine = 'openpyxl')
writer.book = book

df1.to_excel(writer, sheet_name='IR delta', startrow=0, index=False)
writer.save()
writer.close()

I have exported df1 to the excel sheet "IR delta" at this point. Now I want to export df2 to the same sheet but not creating a new sheet. Yet df2 is exported to sheet ""IR delta1".

book = load_workbook(Results)
writer = pd.ExcelWriter(Results, engine = 'openpyxl')
writer.book = book

df2.to_excel(writer, sheet="IR delta", startrow=0, startcol= 10, index=False)
import pandas as pd

Just use merge() method:-

masterdf=df2.merge(df1,on=['Qualifier','CR']) 

Note:- In case the CR column varies ie CR column is different in both dataframes.then use the code below:-

masterdf=df2.merge(df1,on='Qualifier',suffixes=['_df1','df_2']) 

Now save this masterdf :-

writer = pd.ExcelWriter(Results, engine = 'openpyxl')
writer.book = book

masterdf.to_excel(writer, sheet_name='IR delta', startrow=0, index=False)
writer.save()
writer.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM