Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12141

Pandas map two dataframe based on column name mentioned on the other df and partial match to derive new column

$
0
0

I have two dataframes df1 & df2 as below.

import pandas as pddata1 = {'Column1': [1, 2, 3],'Column2': ['Account', 'Biscut', 'Super'],'Column3': ['Funny', 'Super', 'Nice']}df1 = pd.DataFrame(data1)data2 = {'ColumnName':['Column2','Column3','Column1'],'ifExist':['Acc','Sup',3],'TarName':['Account_name','Super_name','Val_3']}df2 = pd.DataFrame(data2)

I want to add new column TarName to the df1 by partially matching the ifExists value from df2 against the ColumnName that Mentioned in the df2 with df1.

My Expected Ouput is:

Column1    column2     column3  TarName1          Account     Funny    Account_Name2          Biscut      Super    Super_name  3          Super       Nice     Val_3

I have tried below code. This code able to partial map but only to one column. With this approach I Need to create dictionaries as many column mapping I have and need to apply as many.

Is there more dynamic approach ?

df2_Column2_dict = df2[df2['ColumnName']=='Column2'].set_index(['ifExist'])['TarName'].to_dict()pat = r'({})'.format('|'.join(df2_Column2_dict.keys()))extracted = df1['Column2'].str.extract(pat, expand=False).dropna()df1['TarName'] =  extracted.apply(lambda x: df2_Column2_dict[x]).reindex(df2.index)print(df1)

Viewing all articles
Browse latest Browse all 12141

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>