Python:如何将数据框导出到现有 Excel sheet 但不创建新的 sheet

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

我想将我的数据帧导出到 Python 中现有 Excel sheet 中的指定列,我尝试了不同的方法,但它们不起作用。我已经将 df1 导出到一个名为“IR delta”的 excel sheet,现在我想将 df2 导出到与 [=18] 相同的 sheet =] 在 运行 一些代码之后生成 df2。但是,创建 excel sheet“IR delta1”而不是导出相同的 sheet“IR delta”。有人可以帮忙吗?非常感谢!

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

请看下面我的代码:

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()

此时我已将 df1 导出到 excel sheet“IR delta”。现在我想将 df2 导出到相同的 sheet 但不创建新的 sheet。然而 df2 被导出到 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

只需使用merge()方法:-

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

注意:- 如果 CR 列不同,即 CR 列在两个 dataframes.then 中不同,请使用以下代码:-

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

现在保存这个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()