-1

我的数据框之一是:

     name    value
0    Harry     a
1    Kenny     b
2    Zoey      h

另一个是:

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

我想如果 dataframe1 的任何名称在 dataframe2 列表中,它应该在 dataframe1 中添加一个名称列“present”,其中包含相应主题的值。

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

更新查询

df1

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

df2 是相同的,期望的结果是

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

2 回答 2

4

我们需要修剪 df1explode然后我们可以做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
于 2021-08-18T14:11:41.883 回答
2
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)
于 2021-08-18T14:29:15.763 回答