python - 如何让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']})
解决方案
可以在不apply
使用str.extract和map的情况下完成:
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()
推荐阅读
- python - 从头开始的神经网络 - 预测单个示例
- javascript - 从不同的浏览器访问 localStorage
- forms - 离子表单动作重定向到内部应用程序页面
- r - 如何在Word中与官员的图像周围制作边框
- sql-server - Docker for Windows:具有 Windows-Container 的持久卷上的 SQL Server 数据库
- ios - 如何检测 Square Reader 硬件通过蓝牙与 iPad 连接?
- php - 从服务器移到另一个服务器后,$_REQUEST 不起作用
- c# - 如何在本地用户中运行应用程序
- excel - 如何在从 Excel 工作表导入消息时使用换行符向 Microsoft 团队发送消息
- python - Python Imports - 参考顶级模块而不是“内级”模块