【问题标题】:How to match two data frames using columns' names of the second dataframe and the value in two columns of the first dataframe如何使用第二个数据帧的列名和第一个数据帧的两列中的值匹配两个数据帧
【发布时间】:2020-10-09 02:44:13
【问题描述】:

假设df_1如下:

col_1 | col_2 | col_3 | ...
12338 | MD   | ...
13438 | LG   | ...
62248 | SM   | ...
92338 | SI   | ...
32818 | SM   | ...
.
.
.

另外,这里是 df_2:

col_1 | MD | LG | SM | SI
12338 | 10 | 29 | 8  | 7
12339 | 15 | 26 | 18 | 17
13438 | 78 | 18 | 77 | 1670
.
.
.

目标是根据 df_2 和 col_1 和 col_2 找到 df_1 中每一行的目标值。 例如,对于 df_1 的第一行,目标值为 10,因为 col_1 为 12338,并且使用 df_2 中的 MD 列。

对于 df_2 的第二行,目标值为 18,因为 col_1 是 13438,并且使用 df_2 中的 LG 列。

col_1 | col_2 | Target | col_3 | ...
12338 | MD    | 10     | ...
13438 | LG    | 18     | ...
.
.
.

我想对一个非常大的数据框做上述过程。

我知道我可以使用合并甚至使用一些 if 条件来做到这一点,但我正在寻找一种非常高效和新颖的方式,但速度太快了。任何创新的想法都将不胜感激。

【问题讨论】:

    标签: python pandas merge


    【解决方案1】:

    检查lookup

    df1['Target']=df2.set_index('col_1').lookup(df1.col_1, df1.col_2)
    

    【讨论】:

      猜你喜欢
      • 2021-03-10
      • 2021-08-02
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-28
      相关资源
      最近更新 更多