【问题标题】:pandas assert_frame_equal behavior熊猫 assert_frame_equal 行为
【发布时间】:2018-02-28 11:39:35
【问题描述】:

我正在尝试将两个 DataFrame 与 pandas 测试 assert_frame_equal 进行比较。这些帧包含我想与一些用户定义的精度进行比较的浮点数。

assert_frame_equal 中的 check_less_precise 参数似乎表明我可以指定小数点后的位数进行比较。引用 API 参考页面 -

check_less_precise:指定比较精度。仅在 check_exact 为 False 时使用。比较小数点后的 5 位 (False) 或 3 位 (True)。如果是int,则指定要比较的数字

API Reference

但是,当浮点数小于 1 时,这似乎不起作用。

这会引发 AssertionError

import pandas as pd

expected = pd.DataFrame([{"col": 0.1}])
output = pd.DataFrame([{"col": 0.12}])
pd.testing.assert_frame_equal(expected, output, check_less_precise=1)

虽然没有

expected = pd.DataFrame([{"col": 1.1}])
output = pd.DataFrame([{"col": 1.12}])
pd.testing.assert_frame_equal(expected, output, check_less_precise=1)

有人可以帮助解释这种行为吗,这是一个错误吗?

【问题讨论】:

    标签: python pandas testing


    【解决方案1】:

    我仔细研究了源代码,发现了发生了什么。最终函数 decimal_almost_equal 被调用,在普通 Python 中看起来像这样(在 Cython 中)。

    def decimal_almost_equal(desired, actual, decimal):
        return abs(desired - actual) < (0.5 * 10.0 ** -decimal)
    

    见the source code here这是对函数的实际调用:

    decimal_almost_equal(1, fb / fa, decimal)
    

    在这个例子中的位置

    fa = .1
    fb = .12
    decimal = 1
    

    所以函数调用就变成了

    decimal_almost_equal(1, 1.2, 1)
    

    decimal_almost_equal 评估为

    abs(1 - 1.2) < .5  * 10 ** -1
    

    或者

    .2 < .05
    

    这是False。

    所以比较是基于百分比差异,而不是看起来的总差异。

    如果您想进行绝对比较,请查看np.allclose。

    np.allclose(expected, output, atol=.1)
    True
    

    【讨论】:

    • 因此,与 fa = 0.0 相比,您不会有太多运气
    • 我认为它为 0 采取了不同的路径。故事远不止这个小 sn-p。
    • 谢谢 Ted,我开始认为我是盲人什么的,试图弄清楚为什么我会收到断言错误,尽管它们不应该出现......
    猜你喜欢
    • 2014-10-03
    • 2022-12-18
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 2021-08-08
    • 1970-01-01
    相关资源
    最近更新 更多