如何解决使用 datacompy 库比较熊猫数据框的问题
我正在尝试使用 datacompy 包比较两个数据框。 我看到了一些奇怪的东西。
print(dfA)
req_nbr unit_cost_amt
0 24468868 1.36870
1 24468868 1.36870
2 24468868 1.64952
3 24468868 1.64952
4 24468868 0.83289
5 24468868 0.83289
6 24468868 0.83289
7 24468868 0.83289
print(dfB)
req_nbr unit_cost_amt
0 24468868 1.36870
1 24468868 1.36870
2 24468868 1.64952
3 24468868 1.64952
4 24468868 0.83289
5 24468868 0.83289
6 24468868 0.83289
7 24468868 0.83289
两个数据帧是相同的并且具有相同的数据类型。
dfA['unit_cost_amt'].dtype
dtype('float64')
dfB['unit_cost_amt'].dtype
dtype('float64')
现在我正在使用 datacompy 进行比较
compare = datacompy.Compare(
dfA,dfB,# You can also specify a list of columns
join_columns = ['req_nbr'],# Optional,defaults to 0
abs_tol = 0,defaults to 0
rel_tol = 0,defaults to 'df1'
df1_name = 'Old',defaults to 'df2'
df2_name = 'New'
)
print(compare.report())
它显示了差异...
DataComPy Comparison
--------------------
DataFrame Summary
-----------------
DataFrame Columns Rows
0 Old 2 8
1 New 2 8
Column Summary
--------------
Number of columns in common: 2
Number of columns in Old but not in New: 0
Number of columns in New but not in Old: 0
Row Summary
-----------
Matched on: req_nbr
Any duplicates on match values: Yes
Absolute Tolerance: 0
Relative Tolerance: 0
Number of rows in common: 8
Number of rows in Old but not in New: 0
Number of rows in New but not in Old: 0
Number of rows with some compared columns unequal: 4
Number of rows with all compared columns equal: 4
Column Comparison
-----------------
Number of columns compared with some values unequal: 1
Number of columns compared with all values equal: 1
Total number of values which compare unequal: 4
Columns with Unequal Values or Types
------------------------------------
Column Old dtype New dtype # Unequal Max Diff # Null Diff
0 unit_cost_amt float64 float64 4 1.110223e-16 0
Sample Rows with Unequal Values
-------------------------------
req_nbr unit_cost_amt (Old) unit_cost_amt (New)
6 24468868 0.83289 0.83289
7 24468868 0.83289 0.83289
4 24468868 0.83289 0.83289
5 24468868 0.83289 0.83289
知道我在这里做错了什么吗? 令人费解。
解决方法
1e-16 处的最大差异表明它是 a difference in the last mantissa bit,or some rounding / cancellation issue like that。这可能取决于计算差异的方式(如果数字完全相同,则不应该如此)。
您应该设置 rel_tol
或 abs_tol
以避免此类问题 - 这就是这些参数的用途。
例如,datacompy.Compare(...,rel_tol=1e-10)
表示*如果 a
小于 b
,数字 abs(a / b - 1)
和 10^-10
将被视为相同。这个相对阈值足够大,不会偶然发生,也足够小,适用于大多数应用程序。
您可以选择适合您的任何阈值。由于您所有的 unit_cost_amt
似乎都有 5 位数字,因此您也可以使用 abs_tol=1e-6
。
* 通常是这样定义的,但我实际上并没有阅读 datacompy 文档
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。