Skip to content

Commit 74cf2dd

Browse files
jbrockmendelharisbal
authored and
harisbal
committed
Centralize Arithmetic Tests (pandas-dev#19471)
1 parent e25a475 commit 74cf2dd

File tree

6 files changed

+316
-277
lines changed

6 files changed

+316
-277
lines changed

pandas/tests/frame/test_arithmetic.py

+103
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,114 @@
11
# -*- coding: utf-8 -*-
22

3+
import pytest
34
import numpy as np
45

56
import pandas as pd
67
import pandas.util.testing as tm
78

89

10+
# -------------------------------------------------------------------
11+
# Comparisons
12+
13+
class TestFrameComparisons(object):
14+
def test_df_boolean_comparison_error(self):
15+
# GH#4576
16+
# boolean comparisons with a tuple/list give unexpected results
17+
df = pd.DataFrame(np.arange(6).reshape((3, 2)))
18+
19+
# not shape compatible
20+
with pytest.raises(ValueError):
21+
df == (2, 2)
22+
with pytest.raises(ValueError):
23+
df == [2, 2]
24+
25+
def test_df_float_none_comparison(self):
26+
df = pd.DataFrame(np.random.randn(8, 3), index=range(8),
27+
columns=['A', 'B', 'C'])
28+
29+
with pytest.raises(TypeError):
30+
df.__eq__(None)
31+
32+
def test_df_string_comparison(self):
33+
df = pd.DataFrame([{"a": 1, "b": "foo"}, {"a": 2, "b": "bar"}])
34+
mask_a = df.a > 1
35+
tm.assert_frame_equal(df[mask_a], df.loc[1:1, :])
36+
tm.assert_frame_equal(df[-mask_a], df.loc[0:0, :])
37+
38+
mask_b = df.b == "foo"
39+
tm.assert_frame_equal(df[mask_b], df.loc[0:0, :])
40+
tm.assert_frame_equal(df[-mask_b], df.loc[1:1, :])
41+
42+
@pytest.mark.parametrize('opname', ['eq', 'ne', 'gt', 'lt', 'ge', 'le'])
43+
def test_df_flex_cmp_constant_return_types(self, opname):
44+
# GH#15077, non-empty DataFrame
45+
df = pd.DataFrame({'x': [1, 2, 3], 'y': [1., 2., 3.]})
46+
const = 2
47+
48+
result = getattr(df, opname)(const).get_dtype_counts()
49+
tm.assert_series_equal(result, pd.Series([2], ['bool']))
50+
51+
@pytest.mark.parametrize('opname', ['eq', 'ne', 'gt', 'lt', 'ge', 'le'])
52+
def test_df_flex_cmp_constant_return_types_empty(self, opname):
53+
# GH#15077 empty DataFrame
54+
df = pd.DataFrame({'x': [1, 2, 3], 'y': [1., 2., 3.]})
55+
const = 2
56+
57+
empty = df.iloc[:0]
58+
result = getattr(empty, opname)(const).get_dtype_counts()
59+
tm.assert_series_equal(result, pd.Series([2], ['bool']))
60+
61+
62+
# -------------------------------------------------------------------
63+
# Arithmetic
64+
65+
class TestFrameArithmetic(object):
66+
67+
@pytest.mark.xfail(reason='GH#7996 datetime64 units not converted to nano')
68+
def test_df_sub_datetime64_not_ns(self):
69+
df = pd.DataFrame(pd.date_range('20130101', periods=3))
70+
dt64 = np.datetime64('2013-01-01')
71+
assert dt64.dtype == 'datetime64[D]'
72+
res = df - dt64
73+
expected = pd.DataFrame([pd.Timedelta(days=0), pd.Timedelta(days=1),
74+
pd.Timedelta(days=2)])
75+
tm.assert_frame_equal(res, expected)
76+
77+
@pytest.mark.parametrize('data', [
78+
[1, 2, 3],
79+
[1.1, 2.2, 3.3],
80+
[pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-02'), pd.NaT],
81+
['x', 'y', 1]])
82+
@pytest.mark.parametrize('dtype', [None, object])
83+
def test_df_radd_str_invalid(self, dtype, data):
84+
df = pd.DataFrame(data, dtype=dtype)
85+
with pytest.raises(TypeError):
86+
'foo_' + df
87+
88+
@pytest.mark.parametrize('dtype', [None, object])
89+
def test_df_with_dtype_radd_int(self, dtype):
90+
df = pd.DataFrame([1, 2, 3], dtype=dtype)
91+
expected = pd.DataFrame([2, 3, 4], dtype=dtype)
92+
result = 1 + df
93+
tm.assert_frame_equal(result, expected)
94+
result = df + 1
95+
tm.assert_frame_equal(result, expected)
96+
97+
@pytest.mark.parametrize('dtype', [None, object])
98+
def test_df_with_dtype_radd_nan(self, dtype):
99+
df = pd.DataFrame([1, 2, 3], dtype=dtype)
100+
expected = pd.DataFrame([np.nan, np.nan, np.nan], dtype=dtype)
101+
result = np.nan + df
102+
tm.assert_frame_equal(result, expected)
103+
result = df + np.nan
104+
tm.assert_frame_equal(result, expected)
105+
106+
def test_df_radd_str(self):
107+
df = pd.DataFrame(['x', np.nan, 'x'])
108+
tm.assert_frame_equal('a' + df, pd.DataFrame(['ax', np.nan, 'ax']))
109+
tm.assert_frame_equal(df + 'a', pd.DataFrame(['xa', np.nan, 'xa']))
110+
111+
9112
class TestPeriodFrameArithmetic(object):
10113

11114
def test_ops_frame_period(self):

pandas/tests/frame/test_operators.py

+1-90
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from numpy import nan, random
1111
import numpy as np
1212

13-
from pandas.compat import lrange, range
13+
from pandas.compat import range
1414
from pandas import compat
1515
from pandas import (DataFrame, Series, MultiIndex, Timestamp,
1616
date_range)
@@ -28,53 +28,6 @@
2828
_check_mixed_int)
2929

3030

31-
class TestDataFrameArithmetic(object):
32-
33-
@pytest.mark.xfail(reason='GH#7996 datetime64 units not converted to nano')
34-
def test_frame_sub_datetime64_not_ns(self):
35-
df = pd.DataFrame(date_range('20130101', periods=3))
36-
dt64 = np.datetime64('2013-01-01')
37-
assert dt64.dtype == 'datetime64[D]'
38-
res = df - dt64
39-
expected = pd.DataFrame([pd.Timedelta(days=0), pd.Timedelta(days=1),
40-
pd.Timedelta(days=2)])
41-
tm.assert_frame_equal(res, expected)
42-
43-
@pytest.mark.parametrize('data', [
44-
[1, 2, 3],
45-
[1.1, 2.2, 3.3],
46-
[pd.Timestamp('2011-01-01'), pd.Timestamp('2011-01-02'), pd.NaT],
47-
['x', 'y', 1]])
48-
@pytest.mark.parametrize('dtype', [None, object])
49-
def test_frame_radd_str_invalid(self, dtype, data):
50-
df = DataFrame(data, dtype=dtype)
51-
with pytest.raises(TypeError):
52-
'foo_' + df
53-
54-
@pytest.mark.parametrize('dtype', [None, object])
55-
def test_frame_with_dtype_radd_int(self, dtype):
56-
df = pd.DataFrame([1, 2, 3], dtype=dtype)
57-
expected = pd.DataFrame([2, 3, 4], dtype=dtype)
58-
result = 1 + df
59-
assert_frame_equal(result, expected)
60-
result = df + 1
61-
assert_frame_equal(result, expected)
62-
63-
@pytest.mark.parametrize('dtype', [None, object])
64-
def test_frame_with_dtype_radd_nan(self, dtype):
65-
df = pd.DataFrame([1, 2, 3], dtype=dtype)
66-
expected = pd.DataFrame([np.nan, np.nan, np.nan], dtype=dtype)
67-
result = np.nan + df
68-
assert_frame_equal(result, expected)
69-
result = df + np.nan
70-
assert_frame_equal(result, expected)
71-
72-
def test_frame_radd_str(self):
73-
df = pd.DataFrame(['x', np.nan, 'x'])
74-
assert_frame_equal('a' + df, pd.DataFrame(['ax', np.nan, 'ax']))
75-
assert_frame_equal(df + 'a', pd.DataFrame(['xa', np.nan, 'xa']))
76-
77-
7831
class TestDataFrameOperators(TestData):
7932

8033
def test_operators(self):
@@ -714,22 +667,6 @@ def _test_seq(df, idx_ser, col_ser):
714667
exp = DataFrame({'col': [False, True, False]})
715668
assert_frame_equal(result, exp)
716669

717-
def test_return_dtypes_bool_op_costant(self):
718-
# GH15077
719-
df = DataFrame({'x': [1, 2, 3], 'y': [1., 2., 3.]})
720-
const = 2
721-
722-
# not empty DataFrame
723-
for op in ['eq', 'ne', 'gt', 'lt', 'ge', 'le']:
724-
result = getattr(df, op)(const).get_dtype_counts()
725-
tm.assert_series_equal(result, Series([2], ['bool']))
726-
727-
# empty DataFrame
728-
empty = df.iloc[:0]
729-
for op in ['eq', 'ne', 'gt', 'lt', 'ge', 'le']:
730-
result = getattr(empty, op)(const).get_dtype_counts()
731-
tm.assert_series_equal(result, Series([2], ['bool']))
732-
733670
def test_dti_tz_convert_to_utc(self):
734671
base = pd.DatetimeIndex(['2011-01-01', '2011-01-02',
735672
'2011-01-03'], tz='UTC')
@@ -1009,22 +946,6 @@ def test_comparison_protected_from_errstate(self):
1009946
result = (missing_df < 0).values
1010947
tm.assert_numpy_array_equal(result, expected)
1011948

1012-
def test_string_comparison(self):
1013-
df = DataFrame([{"a": 1, "b": "foo"}, {"a": 2, "b": "bar"}])
1014-
mask_a = df.a > 1
1015-
assert_frame_equal(df[mask_a], df.loc[1:1, :])
1016-
assert_frame_equal(df[-mask_a], df.loc[0:0, :])
1017-
1018-
mask_b = df.b == "foo"
1019-
assert_frame_equal(df[mask_b], df.loc[0:0, :])
1020-
assert_frame_equal(df[-mask_b], df.loc[1:1, :])
1021-
1022-
def test_float_none_comparison(self):
1023-
df = DataFrame(np.random.randn(8, 3), index=lrange(8),
1024-
columns=['A', 'B', 'C'])
1025-
1026-
pytest.raises(TypeError, df.__eq__, None)
1027-
1028949
def test_boolean_comparison(self):
1029950

1030951
# GH 4576
@@ -1091,16 +1012,6 @@ def test_boolean_comparison(self):
10911012
result = df == tup
10921013
assert_frame_equal(result, expected)
10931014

1094-
def test_boolean_comparison_error(self):
1095-
1096-
# GH 4576
1097-
# boolean comparisons with a tuple/list give unexpected results
1098-
df = DataFrame(np.arange(6).reshape((3, 2)))
1099-
1100-
# not shape compatible
1101-
pytest.raises(ValueError, lambda: df == (2, 2))
1102-
pytest.raises(ValueError, lambda: df == [2, 2])
1103-
11041015
def test_combine_generic(self):
11051016
df1 = self.frame
11061017
df2 = self.frame.loc[self.frame.index[:-5], ['A', 'B', 'C']]

0 commit comments

Comments
 (0)