如何检查Pandas中的另一个数据帧中是否存在两列的组合值



我有多个具有两个公共列的dfs

样品df

user_id and event_date
abc   |  1st june
abc   |  2nd June
cdf   | 15th july
dfg   | 17th July

我想检查df1中特定event_date上的user_id是否也存在于df2、df3、df4和df5 中

我怎么找到这个?

我尝试了以下方法,但它只起作用;CCD_ 3";考虑到而不是";CCD_ 4";

方法1:

upi_sms =df1.assign(Insms=df2.user_id.isin(df1.user_id).astype(int))

方法2:合并数据帧on = [user_id, event_date]

这些都没有给我带来预期的结果。

预期结果:

Combination of abc and 1st June should exist in df2 

我该如何做到这一点?

我会按照以下方式来做,考虑一个简单的例子:

import pandas as pd
df1 = pd.DataFrame({'x':['A','B','C'],'y':[1,2,3]})
df2 = pd.DataFrame({'x':['C','A','B'],'y':[3,2,1]})
df3 = pd.DataFrame({'x':['A','B','C'],'y':[0,0,0]})

假设您对df1的最后一行感兴趣,即其中x是C,y是3。这样的行也存在于df2(1st(中,但不存在于其中存在x为C但具有不同的行的df3中。

row = tuple(df1.iloc[-1]) # get last row of df1 as tuple
print(row in df2.itertuples(index=False)) # True
print(row in df3.itertuples(index=False)) # False

注意,通过index=False很重要,因为我们不想考虑数字在pandas.DataFrame内的位置

最新更新