首页 > 解决方案 > 如何在没有匹配索引的情况下比较来自两个 DF 的两个日期?

问题描述

df1
  USERID    DATE
     1       1/1/2018
     1       1/2/2018
     1       1/3/2018
     2       1/2/2018
     2       1/3/2018
     3       1/3/2018

df2
  USERID    DATE
     1       1/1/2018        
     2       1/2/2018         
     3       1/3/2018

我想比较datefrom df2to df1that 属于同一个USERID来判断该行是否df1也存在于df2

Result:
  USERID      DATE       Exists
     1       1/1/2018     True
     1       1/2/2018     False
     1       1/3/2018     False
     2       1/2/2018     True
     2       1/3/2018     False
     3       1/3/2018     True

我想做相当于 np.where((df1['DATE'] == df2['DATE']), True, False) 但现在返回错误Can only compare identically-labeled Series objects

标签: pythonpandasnumpy

解决方案


你可以这样做merge

# create a new column 
df2['Exists'] = True

df3 = pd.merge(df1,df2,on=['USERID','DATE'],how='outer').fillna(False)

  USERID    DATE    Exists
0   1   1/1/2018    True
1   1   1/2/2018    False
2   1   1/3/2018    False
3   2   1/2/2018    True
4   2   1/3/2018    False
5   3   1/3/2018    True

推荐阅读