本文整理汇总了Python中pandas.util.testing.assert_almost_equal方法的典型用法代码示例。如果您正苦于以下问题:Python testing.assert_almost_equal方法的具体用法?Python testing.assert_almost_equal怎么用?Python testing.assert_almost_equal使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pandas.util.testing
的用法示例。
在下文中一共展示了testing.assert_almost_equal方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_set_value
# 需要导入模块: from pandas.util import testing [as 别名]
# 或者: from pandas.util.testing import assert_almost_equal [as 别名]
def test_set_value(self):
for item in self.panel.items:
for mjr in self.panel.major_axis[::2]:
for mnr in self.panel.minor_axis:
with tm.assert_produces_warning(FutureWarning,
check_stacklevel=False):
self.panel.set_value(item, mjr, mnr, 1.)
tm.assert_almost_equal(self.panel[item][mnr][mjr], 1.)
# resize
with catch_warnings():
simplefilter("ignore", FutureWarning)
res = self.panel.set_value('ItemE', 'foo', 'bar', 1.5)
assert isinstance(res, Panel)
assert res is not self.panel
assert res.get_value('ItemE', 'foo', 'bar') == 1.5
res3 = self.panel.set_value('ItemE', 'foobar', 'baz', 5)
assert is_float_dtype(res3['ItemE'].values)
msg = ("There must be an argument for each "
"axis plus the value provided")
with pytest.raises(TypeError, match=msg):
self.panel.set_value('a')
示例2: test_constructor_cast
# 需要导入模块: from pandas.util import testing [as 别名]
# 或者: from pandas.util.testing import assert_almost_equal [as 别名]
def test_constructor_cast(self):
zero_filled = self.panel.fillna(0)
casted = Panel(zero_filled._data, dtype=int)
casted2 = Panel(zero_filled.values, dtype=int)
exp_values = zero_filled.values.astype(int)
assert_almost_equal(casted.values, exp_values)
assert_almost_equal(casted2.values, exp_values)
casted = Panel(zero_filled._data, dtype=np.int32)
casted2 = Panel(zero_filled.values, dtype=np.int32)
exp_values = zero_filled.values.astype(np.int32)
assert_almost_equal(casted.values, exp_values)
assert_almost_equal(casted2.values, exp_values)
# can't cast
data = [[['foo', 'bar', 'baz']]]
pytest.raises(ValueError, Panel, data, dtype=float)
示例3: test_apply
# 需要导入模块: from pandas.util import testing [as 别名]
# 或者: from pandas.util.testing import assert_almost_equal [as 别名]
def test_apply(frame):
applied = frame.apply(np.sqrt)
assert isinstance(applied, SparseDataFrame)
tm.assert_almost_equal(applied.values, np.sqrt(frame.values))
# agg / broadcast
with tm.assert_produces_warning(FutureWarning):
broadcasted = frame.apply(np.sum, broadcast=True)
assert isinstance(broadcasted, SparseDataFrame)
with tm.assert_produces_warning(FutureWarning):
exp = frame.to_dense().apply(np.sum, broadcast=True)
tm.assert_frame_equal(broadcasted.to_dense(), exp)
applied = frame.apply(np.sum)
tm.assert_series_equal(applied,
frame.to_dense().apply(nanops.nansum).to_sparse())
示例4: test_tdi_total_seconds
# 需要导入模块: from pandas.util import testing [as 别名]
# 或者: from pandas.util.testing import assert_almost_equal [as 别名]
def test_tdi_total_seconds(self):
# GH#10939
# test index
rng = timedelta_range('1 days, 10:11:12.100123456', periods=2,
freq='s')
expt = [1 * 86400 + 10 * 3600 + 11 * 60 + 12 + 100123456. / 1e9,
1 * 86400 + 10 * 3600 + 11 * 60 + 13 + 100123456. / 1e9]
tm.assert_almost_equal(rng.total_seconds(), Index(expt))
# test Series
ser = Series(rng)
s_expt = Series(expt, index=[0, 1])
tm.assert_series_equal(ser.dt.total_seconds(), s_expt)
# with nat
ser[1] = np.nan
s_expt = Series([1 * 86400 + 10 * 3600 + 11 * 60 +
12 + 100123456. / 1e9, np.nan], index=[0, 1])
tm.assert_series_equal(ser.dt.total_seconds(), s_expt)
# with both nat
ser = Series([np.nan, np.nan], dtype='timedelta64[ns]')
tm.assert_series_equal(ser.dt.total_seconds(),
Series([np.nan, np.nan], index=[0, 1]))
示例5: test_errorbar_asymmetrical
# 需要导入模块: from pandas.util import testing [as 别名]
# 或者: from pandas.util.testing import assert_almost_equal [as 别名]
def test_errorbar_asymmetrical(self):
np.random.seed(0)
err = np.random.rand(3, 2, 5)
# each column is [0, 1, 2, 3, 4], [3, 4, 5, 6, 7]...
df = DataFrame(np.arange(15).reshape(3, 5)).T
ax = df.plot(yerr=err, xerr=err / 2)
yerr_0_0 = ax.collections[1].get_paths()[0].vertices[:, 1]
expected_0_0 = err[0, :, 0] * np.array([-1, 1])
tm.assert_almost_equal(yerr_0_0, expected_0_0)
with pytest.raises(ValueError):
df.plot(yerr=err.T)
tm.close()
# This XPASSES when tested with mpl == 3.0.1
示例6: _check_data
# 需要导入模块: from pandas.util import testing [as 别名]
# 或者: from pandas.util.testing import assert_almost_equal [as 别名]
def _check_data(self, xp, rs):
"""
Check each axes has identical lines
Parameters
----------
xp : matplotlib Axes object
rs : matplotlib Axes object
"""
xp_lines = xp.get_lines()
rs_lines = rs.get_lines()
def check_line(xpl, rsl):
xpdata = xpl.get_xydata()
rsdata = rsl.get_xydata()
tm.assert_almost_equal(xpdata, rsdata)
assert len(xp_lines) == len(rs_lines)
[check_line(xpl, rsl) for xpl, rsl in zip(xp_lines, rs_lines)]
tm.close()
示例7: check_chained_cmp_op
# 需要导入模块: from pandas.util import testing [as 别名]
# 或者: from pandas.util.testing import assert_almost_equal [as 别名]
def check_chained_cmp_op(self, lhs, cmp1, mid, cmp2, rhs):
def check_operands(left, right, cmp_op):
return _eval_single_bin(left, cmp_op, right, self.engine)
lhs_new = check_operands(lhs, mid, cmp1)
rhs_new = check_operands(mid, rhs, cmp2)
if lhs_new is not None and rhs_new is not None:
ex1 = 'lhs {0} mid {1} rhs'.format(cmp1, cmp2)
ex2 = 'lhs {0} mid and mid {1} rhs'.format(cmp1, cmp2)
ex3 = '(lhs {0} mid) & (mid {1} rhs)'.format(cmp1, cmp2)
expected = _eval_single_bin(lhs_new, '&', rhs_new, self.engine)
for ex in (ex1, ex2, ex3):
result = pd.eval(ex, engine=self.engine,
parser=self.parser)
tm.assert_almost_equal(result, expected)
示例8: check_pow
# 需要导入模块: from pandas.util import testing [as 别名]
# 或者: from pandas.util.testing import assert_almost_equal [as 别名]
def check_pow(self, lhs, arith1, rhs):
ex = 'lhs {0} rhs'.format(arith1)
expected = self.get_expected_pow_result(lhs, rhs)
result = pd.eval(ex, engine=self.engine, parser=self.parser)
if (is_scalar(lhs) and is_scalar(rhs) and
_is_py3_complex_incompat(result, expected)):
pytest.raises(AssertionError, tm.assert_numpy_array_equal,
result, expected)
else:
tm.assert_almost_equal(result, expected)
ex = '(lhs {0} rhs) {0} rhs'.format(arith1)
result = pd.eval(ex, engine=self.engine, parser=self.parser)
expected = self.get_expected_pow_result(
self.get_expected_pow_result(lhs, rhs), rhs)
tm.assert_almost_equal(result, expected)
示例9: check_compound_invert_op
# 需要导入模块: from pandas.util import testing [as 别名]
# 或者: from pandas.util.testing import assert_almost_equal [as 别名]
def check_compound_invert_op(self, lhs, cmp1, rhs):
skip_these = 'in', 'not in'
ex = '~(lhs {0} rhs)'.format(cmp1)
if is_scalar(rhs) and cmp1 in skip_these:
pytest.raises(TypeError, pd.eval, ex, engine=self.engine,
parser=self.parser, local_dict={'lhs': lhs,
'rhs': rhs})
else:
# compound
if is_scalar(lhs) and is_scalar(rhs):
lhs, rhs = map(lambda x: np.array([x]), (lhs, rhs))
expected = _eval_single_bin(lhs, cmp1, rhs, self.engine)
if is_scalar(expected):
expected = not expected
else:
expected = ~expected
result = pd.eval(ex, engine=self.engine, parser=self.parser)
tm.assert_almost_equal(expected, result)
# make sure the other engines work the same as this one
for engine in self.current_engines:
ev = pd.eval(ex, engine=self.engine, parser=self.parser)
tm.assert_almost_equal(ev, result)
示例10: test_nanvar_ddof
# 需要导入模块: from pandas.util import testing [as 别名]
# 或者: from pandas.util.testing import assert_almost_equal [as 别名]
def test_nanvar_ddof(self):
n = 5
samples = self.prng.uniform(size=(10000, n + 1))
samples[:, -1] = np.nan # Force use of our own algorithm.
variance_0 = nanops.nanvar(samples, axis=1, skipna=True, ddof=0).mean()
variance_1 = nanops.nanvar(samples, axis=1, skipna=True, ddof=1).mean()
variance_2 = nanops.nanvar(samples, axis=1, skipna=True, ddof=2).mean()
# The unbiased estimate.
var = 1.0 / 12
tm.assert_almost_equal(variance_1, var,
check_less_precise=2)
# The underestimated variance.
tm.assert_almost_equal(variance_0, (n - 1.0) / n * var,
check_less_precise=2)
# The overestimated variance.
tm.assert_almost_equal(variance_2, (n - 1.0) / (n - 2.0) * var,
check_less_precise=2)
示例11: test_slice_consolidate_invalidate_item_cache
# 需要导入模块: from pandas.util import testing [as 别名]
# 或者: from pandas.util.testing import assert_almost_equal [as 别名]
def test_slice_consolidate_invalidate_item_cache(self):
# this is chained assignment, but will 'work'
with option_context('chained_assignment', None):
# #3970
df = DataFrame({"aa": compat.lrange(5), "bb": [2.2] * 5})
# Creates a second float block
df["cc"] = 0.0
# caches a reference to the 'bb' series
df["bb"]
# repr machinery triggers consolidation
repr(df)
# Assignment to wrong series
df['bb'].iloc[0] = 0.17
df._clear_item_cache()
tm.assert_almost_equal(df['bb'][0], 0.17)
示例12: test_frame_getitem_setitem_boolean
# 需要导入模块: from pandas.util import testing [as 别名]
# 或者: from pandas.util.testing import assert_almost_equal [as 别名]
def test_frame_getitem_setitem_boolean(
self, multiindex_dataframe_random_data):
frame = multiindex_dataframe_random_data
df = frame.T.copy()
values = df.values
result = df[df > 0]
expected = df.where(df > 0)
tm.assert_frame_equal(result, expected)
df[df > 0] = 5
values[values > 0] = 5
tm.assert_almost_equal(df.values, values)
df[df == 5] = 0
values[values == 5] = 0
tm.assert_almost_equal(df.values, values)
# a df that needs alignment first
df[df[:-1] < 0] = 2
np.putmask(values[:-1], values[:-1] < 0, 2)
tm.assert_almost_equal(df.values, values)
with pytest.raises(TypeError, match='boolean values only'):
df[df * 0] = 2
示例13: check_values
# 需要导入模块: from pandas.util import testing [as 别名]
# 或者: from pandas.util.testing import assert_almost_equal [as 别名]
def check_values(self, f, func, values=False):
if f is None:
return
axes = f.axes
indicies = itertools.product(*axes)
for i in indicies:
result = getattr(f, func)[i]
# check against values
if values:
expected = f.values[i]
else:
expected = f
for a in reversed(i):
expected = expected.__getitem__(a)
tm.assert_almost_equal(result, expected)
示例14: check_reduce
# 需要导入模块: from pandas.util import testing [as 别名]
# 或者: from pandas.util.testing import assert_almost_equal [as 别名]
def check_reduce(self, s, op_name, skipna):
result = getattr(s, op_name)(skipna=skipna)
expected = getattr(s.astype('float64'), op_name)(skipna=skipna)
tm.assert_almost_equal(result, expected)
示例15: check_reduce
# 需要导入模块: from pandas.util import testing [as 别名]
# 或者: from pandas.util.testing import assert_almost_equal [as 别名]
def check_reduce(self, s, op_name, skipna):
if skipna or op_name in ['median', 'skew', 'kurt']:
with pytest.raises(NotImplementedError):
getattr(s, op_name)(skipna=skipna)
else:
result = getattr(s, op_name)(skipna=skipna)
expected = getattr(np.asarray(s), op_name)()
tm.assert_almost_equal(result, expected)