比较两个数据框之间的每个元素

时间:2019-04-26 13:04:17

标签: python pandas

假设我有两个数据框:

# df1
+-----------------------+
| Name_1 |Age| Location |
+-----------------------+
| A    | 18  |    UK    |
| B    | 19  |    US    |
+-----------------------+

# df2
+-------------------------+
| Name_2 | Age | Location |
+-------------------------+
| A    | 18  |    US      |
| B    | 19  |    US      |
+-------------------------+

如何比较所有元素并获得具有布尔值的数据框,该值指示相应的值是否匹配?

所需的输出为:

# desired
+-----------------------+
| Name | Age  | Location|
+-----------------------+
| A    | True |  False  |
| B    | True |  True   |
+-----------------------+

1 个答案:

答案 0 :(得分:3)

如果两个DataFrame中相同的行数和相同的列名分别由DataFrame.set_indexname创建索引,然后进行比较:

df11 = df1.set_index('name')
df22 = df2.set_index('name')
df = (df11 == df22).reset_index()

编辑:如果index的唯一列不同:

df11 = df1.set_index('Name_1')
df22 = df2.set_index('Name_2')
df = (df11 == df22).reset_index()
print (df)
  Name_1   Age  Location
0      A  True     False
1      B  True      True

如果可能的话,另外一列与其他列不同,但是列的长度仍然相同,并且索引的长度也有必要在两者中都设置相同的列名称-例如df22 columns的{​​{1}}:

df11 columns