python - 比较python中的两列并在第一个表中返回匹配项
问题描述
帮助循环比较不同表中的两列并将匹配项返回到第一个表。
data1:
|name | revenue |
|-------|---------|
|Alice | 700 |
|Bob | 1000 |
|Gerry | 300 |
|Alex | 600 |
|Kyle | 800 |
data2:
|Name | revenue |
|-------|---------|
|Bob | 900 |
|Gerry | 400 |
result data1:
|name | revenue | name_result |
|-------|----------|--------------|
|Alice | 700 | |
|Bob | 1000 | Bob |
|Gerry | 300 | Gerry |
|Alex | 600 | |
|Kyle | 800 | |
我尝试使用此代码,但得到了所有空值:
import pandas as pd
import numpy as np
def group_category(category):
for name in data['name']:
if name in data2['Name']:
return name
else: name = ''
return name
data['name_result'] = data['name'].apply(group_category)
解决方案
利用:
def group_category(category):
if category in df2['Name'].unique():
return category
else:
return ''
#Finally:
#Since you are going to use this function on Series so used map() in place of apply()
df1['name_result']=df1['name'].map(group_category)
或者
通过isin()
和where()
:
df1['name_result']=df1['name'].where(df1['name'].isin(df2['Name']),'')
推荐阅读
- c# - HTTP 状态码 - 401/NotAuthorized vs 404/NotFound vs 400/BadRequest
- laravel - laravel 迁移:来自 ssh cpanel 的新鲜
- css - CSS 动画关键帧计算
- javascript - JavaScript 变异观察者
- r - 矩阵到列的转换
- twilio - 在 Twilio 语音会议上如何呼叫多个座席并在第一个应答后挂断
- php - 如何使用取消链接删除 .DS_Store
- flask - 无法在 MethodView 中使用 flask_login 访问当前用户 ID
- java - 当我调整其内容的大小时,JScrollPane 没有调整大小
- terraform - Azure Pipelines:给定 tfplan 时,Terraform Apply 失败