python的双向查找
因此,基本上我有2个类似的数据框架:
table_1
苹果 | 香蕉 | 橙 | 日期 |
---|---|---|---|
1 | 2 | 4 | 2020 |
3 | 5 | 2 | 2021 |
7 | 8 | 9 | 2022 |
Table_2
fruit | Year |
---|---|
苹果 | 2020 |
苹果 | 2021 |
苹果 | 2022 |
苹果 | 2022 |
香蕉 | 香蕉2021 |
香蕉 | 2021 |
2022橙色 | 2020橙色2022 |
橙色 | 2022 |
橙色 | 2022, |
所以我想要根据水果名和各个年份从表_1中查找表_2的水果值。
应该看起来像这样:
水果 | 年号 | 最终结果 |
---|---|---|
苹果 | 2020 | 1 |
苹果 | 2021 | 3 |
苹果 | 2022 | 7 |
香蕉 | 2020 | 2 |
香蕉 | 2021 | 5 |
香蕉 | 2022 | 8 |
橙色 | 2020 | 4 |
橙色 | 2021 | 2 |
橙色 | 2022 | 9 |
在Excel中,一个人可以做这样的事情:
=INDEX(Table1[[Apple]:[Orange]],MATCH([@year],Table1[Date],0),MATCH([@fruit],Table1[[#Headers],[Apple]:[Orange]],0))
但是在Python中可以做什么?
So basically I have 2 DataFrames like this:
Table_1
Apple | Banana | Orange | Date |
---|---|---|---|
1 | 2 | 4 | 2020 |
3 | 5 | 2 | 2021 |
7 | 8 | 9 | 2022 |
Table_2
fruit | year |
---|---|
Apple | 2020 |
Apple | 2021 |
Apple | 2022 |
Banana | 2020 |
Banana | 2021 |
Banana | 2022 |
Orange | 2020 |
Orange | 2021 |
Orange | 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.
The final outcome should look like this:
fruit | year | number |
---|---|---|
Apple | 2020 | 1 |
Apple | 2021 | 3 |
Apple | 2022 | 7 |
Banana | 2020 | 2 |
Banana | 2021 | 5 |
Banana | 2022 | 8 |
Orange | 2020 | 4 |
Orange | 2021 | 2 |
Orange | 2022 | 9 |
In the Excel for an example one can do something like this:
=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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设 pandas ,您可以
Melelt 和
合并
:输出:
Assuming pandas, you can
melt
andmerge
:output: