【问题标题】:Merge two dataframes if data of a column in first dataframe exists in any of the columns of another dataframe in python如果第一个数据框中的列的数据存在于python中另一个数据框的任何列中,则合并两个数据框
【发布时间】:2020-08-07 14:19:59
【问题描述】:

我有两个需要合并的数据框。第一个是:

page            value
shoes           554
sneakers        226
sandals         114
boots           821
T-shirt         213
mobile-phone    284
laptop          361

第二个数据框是:

path1            path2            path3              path4
fashion          footwear         shoes-and-other    shoes
fashion          footwear         shoes-and-other    sneakers
fashion          footwear         sandals            NaN
fashion          footwear         shirts             T-shirt
electronic       devices          mobile-and-tablet  mobile-phone 
electronic       devices          laptop             NaN 

我的预期输出将是:

path1        path2      path3              path4        page         value
fashion      footwear   shoes-and-other    shoes        shoes        554
fashion      footwear   shoes-and-other    sneakers     sneakers     226
fashion      footwear   sandals            NaN          sandals      114
fashion      footwear   shirts             T-shirt      T-shirt      213
electronic   devices    mobile-and-tablet  mobile-phone mobile-phone 284 
electronic   devices    laptop             NaN          laptop       361

如果第一个数据帧中的任何page 字符串存在于第二个数据帧的path1path2,或path3,或path4 列中,我想加入这两个数据帧.请注意,第一个数据帧的page 可能与第二个数据帧的path1 匹配,我有多种情况。

有没有简单的pythonic方式?

【问题讨论】:

  • 你的预期输出是什么。
  • @Erfan 我已经编辑了我的问题。
  • 看起来大多数键都在path4 中,如果缺少值,它们会出现在path3 中,您的实际数据是否相同?
  • 不,正如我所写,page 字符串也可能在path1path2 中找到。但匹配不是部分的,page 的值恰好写在一些path 变量中。

标签: python pandas dataframe join merge


【解决方案1】:

让我们尝试whereffill 创建合并密钥,然后merge

df1['page'] = df1.where(df1.isin(df.page.tolist())).ffill(1).iloc[:,-1]
df1 = df1.merge(df, how='left')
df1
Out[131]: 
        path1     path2              path3         path4          page  value
0     fashion  footwear    shoes-and-other         shoes         shoes    554
1     fashion  footwear    shoes-and-other      sneakers      sneakers    226
2     fashion  footwear            sandals           NaN       sandals    114
3     fashion  footwear             shirts       T-shirt       T-shirt    213
4  electronic   devices  mobile-and-tablet  mobile-phone  mobile-phone    284
5  electronic   devices             laptop           NaN        laptop    361

【讨论】:

    猜你喜欢
    • 2021-01-11
    • 2020-11-05
    • 2021-11-20
    • 2021-03-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    • 2017-08-02
    • 1970-01-01
    相关资源
    最近更新 更多