比较两个Pandas数据框中的两列

时间:2019-03-30 01:46:48

标签: python pandas dataframe

我有两个熊猫数据框:

df1:
a   b   c
1   1   2
2   1   2
3   1   3

df2:
a   b   c 
4   0   2 
5   5   2 
1   1   2 

df1 = {'a': [1, 2, 3], 'b': [1, 1, 1], 'c': [2, 2, 3]}
df2 = {'a': [4, 5, 6], 'b': [0, 5, 1], 'c': [2, 2, 2]}
df1= pd.DataFrame(df1)
df2 = pd.DataFrame(df2)

我正在寻找一个函数,该函数将显示df1和df2在a列中是否包含相同的值。

在示例中,我提供了df1.adf2.a都具有a=1

如果df1和df2没有条目,其中列a中的值相等,则该函数应返回NoneFalse

我该怎么做?我尝试了panda.merge

的几种组合

2 个答案:

答案 0 :(得分:1)

您可以使用设置交集:

def col_intersect(df1, df2, col='a'):
    s1 = set(df1[col])
    s2 = set(df2[col])
    return s1 & s2 else None

尝试使用merge,可以尝试以下操作:

def col_match(df1, df2, col='a'):
    merged = df1.merge(df2, how='inner', on=col)
    if len(merged):
        return merged[col]
    else:
        return None

答案 1 :(得分:1)

使用isinany定义自己的功能

def yourf(x,y):
    if any(x.isin(y)):
        #print(x[x.isin(y)])
        return x[x.isin(y)]
    else: 
        return 'No match' # you can change here to None

Out[316]: 
0    1
Name: a, dtype: int64

yourf(df1.b,df2.c)
Out[318]: 'No match'
相关问题