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
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
import pandas as pd
import numpy as np
df1 = pd.DataFrame({"name":['Harry', 'Kenny', 'Zoey'], "value":["a", "b", "h"]})
df2 = pd.DataFrame({"list": ["Jame, Harry, Noah", "lee, zee"], "topic": ["topic1", "topic2"]})
def add_column(x):
try:
present = df2[df2['list'].str.contains(x)].iloc[0,1]
except IndexError:
present = np.NAN
return present
df1['present'] = df1['name'].apply(add_column)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.