是否有一種內置方法,或者一種快速有效的方法來獲得與 of和/或for inassertDictEqual()相同的功能?rtolatolasset_frame_equal()pandas.testing
我希望能夠比較兩個字典是否等于對應于同一鍵的值,當值在給定的容差范圍內彼此接近時,它們會以相等的方式傳遞。類似于 atol/rtol 對 frame_equal 所做的。
MRE:
import numpy as np
def assert_dicts_almost_equal(d1, d2, rtol=0.01, atol=0.1):
assert len(d1) == len(d2), 'Unequal number of elements.'
for key in d1:
try:
np.testing.assert_allclose(d1[key], d2[key], rtol=rtol, atol=atol)
except AssertionError as msg:
print('Assertion Error for {key}'.format(key=key))
print(msg)
資料:
d = {'A': 0.49, 'B': 0.51}
d0 = {'A': 0.4999999999999991, 'B': 0.5000000000000007, 'C': np.nan}
d1 = {'A': 0.3105572709904508, 'B': 0.5030302993151613, 'C': np.nan}
d2 = {'A': 0.4813463081397519, 'B': 0.5104397084554964, 'C': np.nan}
d3 = {'A': 0.4740668937066489, 'B': 0.5144020381674881, 'C': np.nan}
測驗:
assert_dicts_almost_equal(d0, d)
assert_dicts_almost_equal(d0, d1)
assert_dicts_almost_equal(d0, d2)
assert_dicts_almost_equal(d0, d3)
只有前兩個會引發 Assertion Error,其余的都會通過。
uj5u.com熱心網友回復:
Numpy 的assert_allclose類似。這是要演示的玩具示例。
import numpy as np
dict_a = {'A': np.array([1,2,3]), 'B': np.array([4,5,6]), 'C': np.array([7,8,9])}
dict_b = {'A': np.array([1,2,3]), 'B': np.array([4,5,20]), 'C': np.array([7,8,9])}
for k, v in dict_a.items():
try:
np.testing.assert_allclose(dict_a[k], dict_b[k], atol=2)
print('{k} is close'.format(k=k))
except AssertionError as msg:
print('Assertion Error for {k}'.format(k=k))
print(msg)
輸出:
A is close
Assertion Error for B
Not equal to tolerance rtol=1e-07, atol=2
Mismatched elements: 1 / 3 (33.3%)
Max absolute difference: 14
Max relative difference: 0.7
x: array([4, 5, 6])
y: array([ 4, 5, 20])
C is close
在此示例中,atol 引數設定為 25,其 B 值在絕對容差范圍內。
import numpy as np
dict_a = {'A': np.array([1,2,3]), 'B': np.array([4,5,6]), 'C': np.array([7,8,9])}
dict_b = {'A': np.array([1,2,3]), 'B': np.array([4,5,20]), 'C': np.array([7,8,9])}
for k, v in dict_a.items():
try:
np.testing.assert_allclose(dict_a[k], dict_b[k], atol=25)
print('{k} is close'.format(k=k))
except AssertionError as msg:
print('Assertion Error for {k}'.format(k=k))
print(msg)
輸出:
A is close
B is close
C is close
編輯評論:
根據您的評論,我對此進行了一些更改。現在原始字典是串列和單個值的混合,并且陣列轉換發生在回圈中。與不能處理串列的 math.isclose() 相比,Numpy 更靈活,因為它可以處理串列或單個值。
import numpy as np
import math
dict_a = {'A': [1,2,3], 'B': [1,2,3], 'C': [1,2,3]}
dict_b = {'A': [1,2,3], 'B': 66, 'C': [1,2,3]}
for k, v in dict_a.items():
try:
np.testing.assert_allclose(np.array(dict_a[k]), np.array(dict_b[k]), atol=25)
#math.isclose(dict_a[k], dict_b[k])
print('{k} is close'.format(k=k))
except AssertionError as msg:
print('Assertion Error for {k}'.format(k=k))
print(msg)
輸出:
A is close
Assertion Error for B
Not equal to tolerance rtol=1e-07, atol=25
Mismatched elements: 3 / 3 (100%)
Max absolute difference: 65
Max relative difference: 0.98484848
x: array([1, 2, 3])
y: array(66)
C is close
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/430877.html
下一篇:對.plPerl檔案進行單元測驗
