How can I compare two dataframes, row by row, adding a label (with True/False)?

Viewed 577

I would like to compare two dataframes, which have the same name for the columns. I would like to create another dataframe with an additional column with a label. If val1 = val1 and val2=val2 then add 1 (True), otherwise add 0 (False).

df1:
val1   val2
  3     4
  1     2
  6     7
  8     9

df2:
val1   val2
  3     4
  1     6
  6     7
  8     0

I wish I had a result like this:

df_new:
val1   val2  Label
  3     4      1
  1     2      0
  6     7      1
  8     9      0

How can I do it?

2 Answers

if rows are all aligned, just compare them directly,

df1["Label"] = (df1 == df2).all(axis=1).astype(int)

Try .merge with indicator= parameter:

x = df1.merge(df2, on=["val1", "val2"], indicator="Label", how="left")
x.Label = x.Label.eq("both").astype(int)
print(x)

Prints:

   val1  val2  Label
0     3     4      1
1     1     2      0
2     6     7      1
3     8     9      0
Related