首页 > 解决方案 > 如何让python查找在匹配后返回另一列

问题描述

我有 2 个列表,df 和 df2(这是一个分类法)。我想使用 df2 中的值搜索 df 中的列,并在找到匹配项/或匹配项后从 df2 返回另一个值。我该怎么做?

我的尝试是

import pandas as pd
df = pd.DataFrame({'Name':['a cat', 'grey puppy', 'red dog']})
df
df2 = pd.DataFrame({'BroadTerm':['cat', 'cat', 'dog', 'dog'], 'NarrowTerm':['cat', 'kitten', 'puppy', 'dog']})
NarrowTerm = df2.NarrowTerm.unique().tolist()
df['Animal'] = df['Name'].apply(lambda x: ','.join([part for part in NarrowTerm if part in x]))
df

返回


    Name    Animal
0   a cat   cat
1   grey puppy  puppy
2   red dog dog

但我希望它回来

    Name    Animal
0   a cat   cat
1   grey puppy  dog
2   red dog dog

更新数据

import pandas as pd
import numpy as np
df = pd.DataFrame({'Name':['a cat dog - multiple', 'grey puppy - narrow term', 'a cat puppy', 'reddog - single no spaces', 'acatdog - multiple no spaces']})

标签: pythonpandasdataframe

解决方案


可以在不apply使用str.extractmap的情况下完成:

df['Animal'] = df['Name'].str.extract(pat = f"({'|'.join(df2.NarrowTerm)})")[0].map(dict(df2.iloc[:,::-1].values))

输出:

         Name Animal
0       a cat    cat
1  grey puppy    dog
2     red dog    dog

注意:要创建映射字典,您还可以使用:pd.Series(df2.BroadTerm.values,index=df2.NarrowTerm).to_dict()


推荐阅读