簡體   English   中英

如果第一個 dataframe 中的列的數據存在於 python 中另一個 dataframe 的任何列中,則合並兩個數據幀

[英]Merge two dataframes if data of a column in first dataframe exists in any of the columns of another dataframe in python

我有兩個需要合並的數據框。 第一個是:

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 

我預期的 output 將是:

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字符串存在於第二個數據幀的path1path2path3path4列中,我想加入這兩個數據幀。 請注意,第一個數據幀的page可能與第二個數據幀的path1匹配,我有多種情況。

有沒有簡單的pythonic方式?

讓我們嘗試使用ffill where創建合並鍵,然后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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM