pythonpandasdataframeapplyisin

Add column if value is in another column of another dataframe


One of my dataframe is:

     name    value
0    Harry     a
1    Kenny     b
2    Zoey      h

another is:

     list                    topic
0    Jame, Harry, Noah      topic1
1    lee, zee               topic2  

I want if any of the names of dataframe1 is in list of dataframe2 it should add a name column 'present' in dataframe1 with the values as of the respective topic.

     name    value   present
0    Harry     a      topic1
1    Kenny     b       none
2    Zoey      h       none

UPDATED QUERY

df1

     name        value
0    Harry Lee     a
1    Kenny         b
2    Zoey          h

df2 is same and desired result is

     name    value   present
0 Harry Lee    a      topic1 topic2
1    Kenny     b       none
2    Zoey      h       none

Solution

  • We need to trim the df1 with explode then we can do map

    df1['list'] = df1['list'].str.split(',')
    s = df1.explode('list')
    df['present'] = df.name.map(dict(zip(s['list'],s['topic'])))
    df
    Out[550]: 
        name value present
    0  Harry     a  topic1
    1  Kenny     b     NaN
    2   Zoey     h     NaN