简体   繁体   English

相当于 python 中的 =INDEX(....MATCH())

[英]Equivalent of =INDEX(....MATCH()) in python

I am using Python and Excel at the same time.我同时使用 Python 和 Excel。 I am looking up at a Excel sheet using xlwings , this sheet has the following values:我正在使用xlwings查看 Excel 工作表,该工作表具有以下值:

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我想要做的是让python根据日期比较Excel-DataFrame的值并将数据框值粘贴到Excel工作表中

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到目前为止,我知道如何使用sht_in.range(start,end).value在 Excel 中获取这些值,以及如何使用sht_in.range(start,end).value = df_data将它们插入到 Excel 工作表中,但我不是非常确定如何进行下一步

What you want to do is to read the range from Excel into a dataframe by您想要做的是通过以下方式将 Excel 中的范围读入数据框

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.然后,您可能需要使用 Python 数据框对 Excel 数据框进行左连接。

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).上面的代码按每个数据帧中的第一列合并,并从 xl_df(x 数据集)中删除百分比值。 You should consider merging the columns by column name instead.您应该考虑按列名合并列。

You can then override the data in excel with the new dataframe by然后,您可以使用新的数据框覆盖 excel 中的数据

sht_in.range('A2').value = new_df.values.tolist()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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