I am using Python and Excel at the same time. I am looking up at a Excel sheet using xlwings
, this sheet has the following values:
date rate
31/01/2016 0.60%
29/02/2016 0.60%
31/03/2016 0.60%
30/04/2016 0.60%
31/05/2016 0.60%
30/06/2016 0.60%
31/07/2016 0.60%
31/08/2016 0.60%
30/09/2016 0.60%
31/10/2016 0.40%
30/11/2016 0.40%
....
31/07/2030 1.65%
Then I have a dataframe that looks exactly like that as well, but it has different rates. What I want to do is to make python compare the values Excel-DataFrame based on the dates and paste the dataframe values in the Excel sheet
So far, I know how to grab such values in Excel using sht_in.range(start,end).value
and how to insert them into the Excel sheet using sht_in.range(start,end).value = df_data
, but I am not quite sure how to do the next steps
What you want to do is to read the range from Excel into a dataframe by
xl_df = pd.DataFrame(in_sht.range('A2:B10').value)
Depending on the existing dataframe that you want to compare values to, you may need to rename the columns of this dataframe.
Then you will probably need to perfrom a left join on the Excel-datafram with the Python-dataframe.
new_df = xl_df.merge(py_df, on=0, how='left').drop(columns=['1_x'])
The code above merges by the first column in each dataframe and drops the percentage-values from the xl_df (the x-dataset). You should consider merging the columns by column name instead.
You can then override the data in excel with the new dataframe by
sht_in.range('A2').value = new_df.values.tolist()
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.