【问题标题】:How to merge two dfs based on a substring of the strings in a column and insert values of another column?如何根据列中字符串的子字符串合并两个 dfs 并插入另一列的值?
【发布时间】:2023-02-17 21:32:22
【问题描述】:

我有以下 dfs:

data:

ZIP code urbanisation
1111AA
3916HV

reference:

ZIP code category urbanisation
1111 High
3916 Medium

所以我的数据集中的城市化是空的,我需要使用我在网上找到的城市化度量来填充它。我想要:

  • reference["ZIP code category"] 列与 data["ZIP code"] 的前 4 位数字匹配,但我无法更改实际的邮政编码。也就是说,我想基于子字符串进行匹配,例如使用data["ZIP code"].str[:4]
  • 对于每个匹配项,将reference["urbanisation"]的对应值粘贴到data["urbanisation"]

我试过如下:

pd.merge(
    data, reference,
    left_on=['ZIP code', data["ZIP code"].str[:4]],
    right_on=['ZIP code category', reference["ZIP code category"]]
)

但是,此代码不正确,我不知道如何产生所需的结果。

【问题讨论】:

    标签: python pandas dataframe join merge


    【解决方案1】:

    IIUC 使用:

    data.drop('urbanisation',axis=1).assign(**{'ZIP code category': data["ZIP code"].str[:4]})
        .merge(reference.assign(**{'ZIP code category': data["ZIP code"].astype(str)}),
         on=['ZIP code category'], how='left')
    

    【讨论】:

      猜你喜欢
      • 2021-05-01
      • 1970-01-01
      • 2021-07-28
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      • 2019-07-05
      • 1970-01-01
      相关资源
      最近更新 更多