从另一个数据框中查找匹配元素和 return 其 id- python

Look up the matching element from another data frame and return its id- python

我有一个订单数据框:

items chat_id
curd,vada,rice 74374374h4473
idly,sambar 7949759459h34

我有另一个独特的菜单项数据框,它有自己的特定 ID:

id items
1 idly
2 vada
3 rice
4 curd
5 sambar

现在我想通过在订单数据框中打印其 chat_id 来匹配元素和 return 它的 ID

chat_id id
74374374h4473 4
74374374h4473 2
74374374h4473 3
7949759459h34 1
7949759459h34 5

你有数据框吗df_orders:

            items        chat_id
0  curd,vada,rice  74374374h4473
1     idly,sambar  7949759459h34

和数据框 df_menu:

   id   items
0   1    idly
1   2    vada
2   3    rice
3   4    curd
4   5  sambar

然后:

df_orders["items"] = df_orders["items"].str.split(",")
df_orders = df_orders.explode("items")
print(df_orders.merge(df_menu, on="items")[["chat_id", "id"]])

打印:

         chat_id  id
0  74374374h4473   4
1  74374374h4473   2
2  74374374h4473   3
3  7949759459h34   1
4  7949759459h34   5