使用 pandas 将一个列的值与另一列的所有值进行比较 [英] compare one column value with all the values of other column using pandas

查看:148
本文介绍了使用 pandas 将一个列的值与另一列的所有值进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下值的Excel文件

I have the one excel file which contains the below values

我需要将 a_id 的值与所有 b_id 的值进行比较,如果匹配,我有将 a_flag 的值更新为 1 ,否则为 0

I need to compare a_id value with all the value of b_id and if it matches i have to update the value of a_flag to 1 otherwise 0.

例如,取 a_tag 中的第一个值,即; 123 然后比较 b_id(113,211,222,123)的所有值。当它到达 b_id 中的 123 时,我们可以看到它匹配。因此,我们将 a_flag 的值更新为 1

For example take the first value in a_tag ie; 123 then compare all the values of b_id(113,211,222,123) . When it reaches to 123 in b_id we can see it matches. So we will update the value of a_flag as 1.

就像那样,将所有 a_id 的值与所有的值进行比较b_id 。因此,完成所有操作后,我们在 a_flag 1 0 的值$ c>列。

Just like that take all the values of a_id and compare with all the values of b_id. So after everything done we will have value either 1 or 0 in a_flag column.

完成后,我们将取 b_id 的第一个值,然后与<$ c $中的所有值进行比较c> a_id 列,并相应地更新 b_flag 列。

Once its done we will take the first value of b_id then compare with all the value in a_id column and update b_flag column accordingly.

最后我将获得以下数据。

Finally i will have the below data.

我需要使用熊猫,因为我正在处理大量数据。以下是我的发现,但仅与 b_id 的第一个值进行比较。例如,它将 123 (第一个值< a_id )与 113 (第一个值<< c $ c> b_id )。

I need to this using pandas because i am dealing with large collection of data. Below is my findings but it compare only with the first value of b_id. For example it compares 123(a_id first value) with 113 only (b_id first value).

import pandas as pd 
df1 = pd.read_excel('system_data.xlsx')
df1['a_flag'] = (df3['a_id'] == df3['b_id']).astype(int)


推荐答案

使用 Series.isin 以获得测试会员资格:

Use Series.isin for test membership:

df1['a_flag'] = df3['a_id'].isin(df3['b_id']).astype(int)
df1['b_flag'] = df3['b_id'].isin(df3['a_id']).astype(int)

这篇关于使用 pandas 将一个列的值与另一列的所有值进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆