简体   繁体   English

Python中的双向查找

[英]Two-Way lookup in Python

So basically I have 2 DataFrames like this:所以基本上我有2个这样的DataFrame:

Table_1表格1

Apple苹果 Banana香蕉 Orange橙子 Date日期
1 1 2 2 4 4 2020 2020
3 3 5 5 2 2 2021 2021
7 7 8 8 9 9 2022 2022

Table_2表_2

fruit水果 year
Apple苹果 2020 2020
Apple苹果 2021 2021
Apple苹果 2022 2022
Banana香蕉 2020 2020
Banana香蕉 2021 2021
Banana香蕉 2022 2022
Orange橙子 2020 2020
Orange橙子 2021 2021
Orange橙子 2022 2022

So I want to lookup the values for the fruits for Table_2 from the Table_1 based on the fruit name and the respective year.所以我想根据水果名称和相应的年份从 Table_1 中查找 Table_2 的水果值。

The final outcome should look like this:最终结果应如下所示:

fruit水果 year number数字
Apple苹果 2020 2020 1 1
Apple苹果 2021 2021 3 3
Apple苹果 2022 2022 7 7
Banana香蕉 2020 2020 2 2
Banana香蕉 2021 2021 5 5
Banana香蕉 2022 2022 8 8
Orange橙子 2020 2020 4 4
Orange橙子 2021 2021 2 2
Orange橙子 2022 2022 9 9

In the Excel for an example one can do something like this:以 Excel 为例,可以执行以下操作:

=INDEX(Table1[[Apple]:[Orange]],MATCH([@year],Table1[Date],0),MATCH([@fruit],Table1[[#Headers],[Apple]:[Orange]],0))

But what is the way to do it in Python?但是在 Python 中这样做的方法是什么?

Assuming , you can melt and merge :假设 ,您可以meltmerge

out = (df2
   .merge(df1.rename(columns={'Date': 'year'})
              .melt('year', var_name='fruit', value_name='number'),
           how='left'
          )
)

output:输出:

    fruit  year  number
0   Apple  2020       1
1   Apple  2021       3
2   Apple  2022       7
3  Banana  2020       2
4  Banana  2021       5
5  Banana  2022       8
6  Orange  2020       4
7  Orange  2021       2
8  Orange  2022       9

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

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