pandas isin()函数与列表

时间:2017-08-20 12:30:24

标签: python pandas dataframe

我需要2个数据框,我想使用

  

isin()方法

检查df1和df2中的内容。

当我只比较一列(index1)时 - 结果还可以 - df1.index1中存在2个df1.index1值。

但是当我比较df1和df2的2列(index1,index2)时,对于所有3行,结果都是false,即使有一个公共行(index1 = 3,index2 = 6)。

为什么?

感谢。

def multiply_by_three(f):
    def decorator():
        return f() * 3
return decorator

@multiply_by_three
def add(a, b):  
    return a + b

print(add(1,2)) # returns (1 + 2) * 3 = 9

1 个答案:

答案 0 :(得分:0)

这是因为“如果所有标签都匹配,结果只会在某个位置为真。” (docs)。如果要忽略标签,则需要使用基础numpy数组:

df1[['index1','index2']].isin(df2[['index1', 'index2']].values.ravel())
Out: 
   index1  index2
0   False    True
1    True    True
2    True    True

如果您希望标签与列匹配,可以使用字典:

df1[['index1','index2']].isin(df2[['index1', 'index2']].to_dict('l'))
Out: 
   index1  index2
0   False   False
1    True    True
2    True    True

如果要检查行是否完全匹配,则需要使用merge:

df1.merge(df2, how='left', on=['index1', 'index2'], indicator=True)
Out: 
   A_x  index1  index2  A_y     _merge
0    1       1       4  NaN  left_only
1    2       2       5  NaN  left_only
2    3       3       6  5.0       both

当index1和index2都匹配时,_merge列返回both

相关问题