【问题标题】:Compare two column in python and return matches in first table比较python中的两列并在第一个表中返回匹配项
【发布时间】:2021-09-19 19:10:50
【问题描述】:

帮助循环比较不同表中的两列,并将匹配项返回到第一个表。

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)

【问题讨论】:

  • 您使用哪个模块来处理数据帧? pandasr?
  • 我正在使用熊猫
  • 你读过pandas-merging-101吗?
  • 如果您仍然没有找到方法,请告诉我
  • 不合并怎么办?稍后我想在另一个任务中使用相同的代码: def group_category(category): for name in data['name']: if name in data2['Name']: return 'organic' else: name return name data['name_result '] = data[data['name'] == 'notorganic'].apply(group_category)

标签: python compare cycle


【解决方案1】:

使用:

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']),'')

【讨论】:

  • 如果条件相同,如何覆盖单元格,如果其他条件不变,则保留旧值?
【解决方案2】:

我找到了解决方案:

df1.loc[df1['name'].isin(df2['name_result'].unique()), 'brand'] = 'Adidas Collection'

【讨论】:

    猜你喜欢
    • 2010-11-26
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 2020-12-19
    • 2023-03-04
    相关资源
    最近更新 更多