简体   繁体   English

如何比较 Python 中两个数据框中的两列值?

[英]How to compare two columns values in two dataframes in Python?

I have two dataframes and I have created a "Check" column in second dataframe to check if values in the Total Claims columns are equal.我有两个数据框,我在第二个 dataframe 中创建了一个“检查”列,以检查总索赔列中的值是否相等。 Here are my two dataframes:这是我的两个数据框:

Dataframe 1 Dataframe 1

在此处输入图像描述

Dataframe 2 Dataframe 2

在此处输入图像描述

The code that I used to create the "Check" column comparing Total Claims between the two dataframes was:我用来创建“检查”列比较两个数据框之间的总索赔的代码是:

reported_claims['Check'] =  np.where(reported_claims['Total Claims'].reset_index(drop=True) == df['Total Claims'].reset_index(drop=True) , 'TRUE', 'FALSE')

I noticed that the 7th values in two dataframes are both 31.32 but the check columns says False.我注意到两个数据框中的第 7 个值都是 31.32,但检查列显示为 False。 I was just wondering why is it saying False and how would I fix this problem?我只是想知道为什么它说 False 以及我将如何解决这个问题? Thank you so much for your time!非常感谢您的参与!

The issue arises by comparing two floating point numbers.通过比较两个浮点数会出现问题。 The general rule for most programming languages (including python) is that you can never check if two floats are exactly equal .大多数编程语言(包括 python)的一般规则是你永远不能检查两个浮点数是否完全相等 You have to instead check if the two values are close.您必须改为检查这两个值是否接近。 You can do so using the np.isclose() .您可以使用np.isclose()这样做。 Check this answer for a reference on how to use it.检查此答案以获取有关如何使用它的参考。

Use merge command to join two dataframe and add check column to compare two columns使用合并命令连接两个 dataframe 并添加检查列以比较两列

df = pd.merge(left=Dataframe1, right=Dataframe2, left_on='month', right_on='month')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM