【问题标题】:Look up the matching element from another data frame and return its id- python从另一个数据框中查找匹配的元素并返回其 id-python
【发布时间】:2021-06-26 15:02:33
【问题描述】:

我有一个订单数据框:

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 来匹配元素并返回其 id

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

【问题讨论】:

  • 欢迎来到 SO!请编辑您的问题并将唯一的菜单项数据框更改为表格格式。

标签: python pandas dataframe data-science


【解决方案1】:

如果你有数据框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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 2013-07-22
    相关资源
    最近更新 更多