Python pandas.util.testing.assert_produces_warning() Examples

The following are 30 code examples of pandas.util.testing.assert_produces_warning(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pandas.util.testing , or try the search function .
Example #1
Source File: test_timezones.py    From recruit with Apache License 2.0 7 votes vote down vote up
def test_dti_tz_localize_nonexistent_raise_coerce(self):
        # GH#13057
        times = ['2015-03-08 01:00', '2015-03-08 02:00', '2015-03-08 03:00']
        index = DatetimeIndex(times)
        tz = 'US/Eastern'
        with pytest.raises(pytz.NonExistentTimeError):
            index.tz_localize(tz=tz)

        with pytest.raises(pytz.NonExistentTimeError):
            with tm.assert_produces_warning(FutureWarning):
                index.tz_localize(tz=tz, errors='raise')

        with tm.assert_produces_warning(FutureWarning,
                                        clear=FutureWarning,
                                        check_stacklevel=False):
            result = index.tz_localize(tz=tz, errors='coerce')
        test_times = ['2015-03-08 01:00-05:00', 'NaT',
                      '2015-03-08 03:00-04:00']
        dti = to_datetime(test_times, utc=True)
        expected = dti.tz_convert('US/Eastern')
        tm.assert_index_equal(result, expected) 
Example #2
Source File: test_constructors.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_from_codes_with_float(self):
        # GH21767
        codes = [1.0, 2.0, 0]  # integer, but in float dtype
        dtype = CategoricalDtype(categories=['a', 'b', 'c'])

        with tm.assert_produces_warning(FutureWarning):
            cat = Categorical.from_codes(codes, dtype.categories)
        tm.assert_numpy_array_equal(cat.codes, np.array([1, 2, 0], dtype='i1'))

        with tm.assert_produces_warning(FutureWarning):
            cat = Categorical.from_codes(codes, dtype=dtype)
        tm.assert_numpy_array_equal(cat.codes, np.array([1, 2, 0], dtype='i1'))

        codes = [1.1, 2.0, 0]  # non-integer
        with pytest.raises(ValueError,
                           match="codes need to be array-like integers"):
            Categorical.from_codes(codes, dtype.categories)
        with pytest.raises(ValueError,
                           match="codes need to be array-like integers"):
            Categorical.from_codes(codes, dtype=dtype) 
Example #3
Source File: test_frame.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_sparse_frame_pad_backfill_limit(self):
        index = np.arange(10)
        df = DataFrame(np.random.randn(10, 4), index=index)
        sdf = df.to_sparse()

        result = sdf[:2].reindex(index, method='pad', limit=5)

        with tm.assert_produces_warning(PerformanceWarning):
            expected = sdf[:2].reindex(index).fillna(method='pad')
        expected = expected.to_dense()
        expected.values[-3:] = np.nan
        expected = expected.to_sparse()
        tm.assert_frame_equal(result, expected)

        result = sdf[-2:].reindex(index, method='backfill', limit=5)

        with tm.assert_produces_warning(PerformanceWarning):
            expected = sdf[-2:].reindex(index).fillna(method='backfill')
        expected = expected.to_dense()
        expected.values[:3] = np.nan
        expected = expected.to_sparse()
        tm.assert_frame_equal(result, expected) 
Example #4
Source File: test_astype.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_to_period_tz(self, tz):
        ts = date_range('1/1/2000', '2/1/2000', tz=tz)

        with tm.assert_produces_warning(UserWarning):
            # GH#21333 warning that timezone info will be lost
            result = ts.to_period()[0]
            expected = ts[0].to_period()

        assert result == expected

        expected = date_range('1/1/2000', '2/1/2000').to_period()

        with tm.assert_produces_warning(UserWarning):
            # GH#21333 warning that timezone info will be lost
            result = ts.to_period()

        tm.assert_index_equal(result, expected) 
Example #5
Source File: test_construction.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_construction_with_alt_tz_localize(self, kwargs, tz_aware_fixture):
        tz = tz_aware_fixture
        i = pd.date_range('20130101', periods=5, freq='H', tz=tz)
        kwargs = {key: attrgetter(val)(i) for key, val in kwargs.items()}

        if str(tz) in ('UTC', 'tzutc()'):
            warn = None
        else:
            warn = FutureWarning

        with tm.assert_produces_warning(warn, check_stacklevel=False):
            result = DatetimeIndex(i.tz_localize(None).asi8, **kwargs)
        expected = DatetimeIndex(i, **kwargs)
        tm.assert_index_equal(result, expected)

        # localize into the provided tz
        i2 = DatetimeIndex(i.tz_localize(None).asi8, tz='UTC')
        expected = i.tz_localize(None).tz_localize('UTC')
        tm.assert_index_equal(i2, expected)

        # incompat tz/dtype
        pytest.raises(ValueError, lambda: DatetimeIndex(
            i.tz_localize(None).asi8, dtype=i.dtype, tz='US/Pacific')) 
Example #6
Source File: test_datetime.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_asarray_tz_naive(self):
        # This shouldn't produce a warning.
        idx = pd.date_range('2000', periods=2)
        # M8[ns] by default
        with tm.assert_produces_warning(None):
            result = np.asarray(idx)

        expected = np.array(['2000-01-01', '2000-01-02'], dtype='M8[ns]')
        tm.assert_numpy_array_equal(result, expected)

        # optionally, object
        with tm.assert_produces_warning(None):
            result = np.asarray(idx, dtype=object)

        expected = np.array([pd.Timestamp('2000-01-01'),
                             pd.Timestamp('2000-01-02')])
        tm.assert_numpy_array_equal(result, expected) 
Example #7
Source File: test_series.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_concat_different_kind(self):
        val1 = np.array([1, 2, np.nan, np.nan, 0, np.nan])
        val2 = np.array([3, np.nan, 4, 0, 0])

        sparse1 = pd.SparseSeries(val1, name='x', kind='integer')
        sparse2 = pd.SparseSeries(val2, name='y', kind='block', fill_value=0)

        with tm.assert_produces_warning(PerformanceWarning):
            res = pd.concat([sparse1, sparse2])
        exp = pd.concat([pd.Series(val1), pd.Series(val2)])
        exp = pd.SparseSeries(exp, kind='integer')
        tm.assert_sp_series_equal(res, exp)

        with tm.assert_produces_warning(PerformanceWarning):
            res = pd.concat([sparse2, sparse1])
        exp = pd.concat([pd.Series(val2), pd.Series(val1)])
        exp = pd.SparseSeries(exp, kind='block', fill_value=0)
        tm.assert_sp_series_equal(res, exp) 
Example #8
Source File: test_datetime.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_asarray_tz_aware(self):
        tz = 'US/Central'
        idx = pd.date_range('2000', periods=2, tz=tz)
        expected = np.array(['2000-01-01T06', '2000-01-02T06'], dtype='M8[ns]')
        # We warn by default and return an ndarray[M8[ns]]
        with tm.assert_produces_warning(FutureWarning):
            result = np.asarray(idx)

        tm.assert_numpy_array_equal(result, expected)

        # Old behavior with no warning
        with tm.assert_produces_warning(None):
            result = np.asarray(idx, dtype="M8[ns]")

        tm.assert_numpy_array_equal(result, expected)

        # Future behavior with no warning
        expected = np.array([pd.Timestamp("2000-01-01", tz=tz),
                             pd.Timestamp("2000-01-02", tz=tz)])
        with tm.assert_produces_warning(None):
            result = np.asarray(idx, dtype=object)

        tm.assert_numpy_array_equal(result, expected) 
Example #9
Source File: test_arithmetic.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_dti_shift_int(self):
        rng = date_range('1/1/2000', periods=20)

        with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
            # GH#22535
            result = rng + 5

        expected = rng.shift(5)
        tm.assert_index_equal(result, expected)

        with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
            # GH#22535
            result = rng - 5

        expected = rng.shift(-5)
        tm.assert_index_equal(result, expected) 
Example #10
Source File: test_apply.py    From recruit with Apache License 2.0 6 votes vote down vote up
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()) 
Example #11
Source File: test_panel.py    From recruit with Apache License 2.0 6 votes vote down vote up
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') 
Example #12
Source File: test_base.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_union_sort_other_incomparable(self):
        # https://github.com/pandas-dev/pandas/issues/24959
        idx = pd.Index([1, pd.Timestamp('2000')])
        # default (sort=None)
        with tm.assert_produces_warning(RuntimeWarning):
            result = idx.union(idx[:1])

        tm.assert_index_equal(result, idx)

        # sort=None
        with tm.assert_produces_warning(RuntimeWarning):
            result = idx.union(idx[:1], sort=None)
        tm.assert_index_equal(result, idx)

        # sort=False
        result = idx.union(idx[:1], sort=False)
        tm.assert_index_equal(result, idx) 
Example #13
Source File: test_period.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_pindex_multiples(self):
        with tm.assert_produces_warning(FutureWarning):
            pi = PeriodIndex(start='1/1/11', end='12/31/11', freq='2M')
        expected = PeriodIndex(['2011-01', '2011-03', '2011-05', '2011-07',
                                '2011-09', '2011-11'], freq='2M')
        tm.assert_index_equal(pi, expected)
        assert pi.freq == offsets.MonthEnd(2)
        assert pi.freqstr == '2M'

        pi = period_range(start='1/1/11', end='12/31/11', freq='2M')
        tm.assert_index_equal(pi, expected)
        assert pi.freq == offsets.MonthEnd(2)
        assert pi.freqstr == '2M'

        pi = period_range(start='1/1/11', periods=6, freq='2M')
        tm.assert_index_equal(pi, expected)
        assert pi.freq == offsets.MonthEnd(2)
        assert pi.freqstr == '2M' 
Example #14
Source File: test_construction.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_deprecated(self):
        ivs = [Interval(0, 1), Interval(1, 2)]
        with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
            IntervalIndex.from_intervals(ivs) 
Example #15
Source File: test_construction.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_range_kwargs_deprecated(self):
        # GH#23919
        with tm.assert_produces_warning(FutureWarning):
            DatetimeIndex(start='1/1/2000', end='1/10/2000', freq='D') 
Example #16
Source File: test_construction.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_verify_integrity_deprecated(self):
        # GH#23919
        with tm.assert_produces_warning(FutureWarning):
            DatetimeIndex(['1/1/2000'], verify_integrity=False) 
Example #17
Source File: test_interval.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_itemsize(self):
        # GH 19209
        left = np.arange(0, 4, dtype='i8')
        right = np.arange(1, 5, dtype='i8')
        expected = 16  # 8 * 2

        with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
            result = IntervalIndex.from_arrays(left, right).itemsize

        assert result == expected 
Example #18
Source File: test_construction.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_constructor_use_start_freq(self):
        # GH #1118
        p = Period('4/2/2012', freq='B')
        with tm.assert_produces_warning(FutureWarning):
            index = PeriodIndex(start=p, periods=10)
        expected = period_range(start='4/2/2012', periods=10, freq='B')
        tm.assert_index_equal(index, expected)

        index = period_range(start=p, periods=10)
        tm.assert_index_equal(index, expected) 
Example #19
Source File: test_construction.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_constructor_range_based_deprecated(self):
        with tm.assert_produces_warning(FutureWarning):
            pi = PeriodIndex(freq='A', start='1/1/2001', end='12/1/2009')
        assert len(pi) == 9 
Example #20
Source File: test_arithmetic.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_tdi_add_integer_array(self, box):
        # GH#19959
        rng = timedelta_range('1 days 09:00:00', freq='H', periods=3)
        other = box([4, 3, 2])
        expected = TimedeltaIndex(['1 day 13:00:00'] * 3)
        with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
            # GH#22535
            result = rng + other
            tm.assert_index_equal(result, expected)

        with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
            # GH#22535
            result = other + rng
            tm.assert_index_equal(result, expected) 
Example #21
Source File: test_scalar_compat.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_dti_timestamp_fields(self, field):
        # extra fields from DatetimeIndex like quarter and week
        idx = tm.makeDateIndex(100)
        expected = getattr(idx, field)[-1]
        if field == 'weekday_name':
            with tm.assert_produces_warning(FutureWarning,
                                            check_stacklevel=False):
                result = getattr(Timestamp(idx[-1]), field)
        else:
            result = getattr(Timestamp(idx[-1]), field)
        assert result == expected 
Example #22
Source File: test_frozen.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_searchsorted(self):
        expected = 2
        assert self.container.searchsorted(7) == expected

        with tm.assert_produces_warning(FutureWarning):
            assert self.container.searchsorted(v=7) == expected 
Example #23
Source File: test_frozen.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_constructor_warns(self):
        # see gh-9031
        with tm.assert_produces_warning(FutureWarning):
            FrozenNDArray([1, 2, 3]) 
Example #24
Source File: test_base.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_tab_complete_warning(self, ip):
        # https://github.com/pandas-dev/pandas/issues/16409
        pytest.importorskip('IPython', minversion="6.0.0")
        from IPython.core.completer import provisionalcompleter

        code = "import pandas as pd; idx = pd.Index([1, 2])"
        ip.run_code(code)
        with tm.assert_produces_warning(None):
            with provisionalcompleter('ignore'):
                list(ip.Completer.completions('idx.', 4)) 
Example #25
Source File: test_base.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_get_duplicates_deprecated(self):
        index = pd.Index([1, 2, 3])
        with tm.assert_produces_warning(FutureWarning):
            index.get_duplicates() 
Example #26
Source File: test_base.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_outer_join_sort(self):
        left_index = Index(np.random.permutation(15))
        right_index = tm.makeDateIndex(10)

        with tm.assert_produces_warning(RuntimeWarning):
            result = left_index.join(right_index, how='outer')

        # right_index in this case because DatetimeIndex has join precedence
        # over Int64Index
        with tm.assert_produces_warning(RuntimeWarning):
            expected = right_index.astype(object).union(
                left_index.astype(object))

        tm.assert_index_equal(result, expected) 
Example #27
Source File: test_base.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_summary_deprecated(self):
        ind = Index(['{other}%s', "~:{range}:0"], name='A')

        with tm.assert_produces_warning(FutureWarning):
            ind.summary() 
Example #28
Source File: datetimelike.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_asobject_deprecated(self):
        # GH18572
        d = self.create_index()
        with tm.assert_produces_warning(FutureWarning):
            i = d.asobject
        assert isinstance(i, pd.Index) 
Example #29
Source File: test_arithmetic.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_tdi_sub_integer_array(self, box):
        # GH#19959
        rng = timedelta_range('9H', freq='H', periods=3)
        other = box([4, 3, 2])
        expected = TimedeltaIndex(['5H', '7H', '9H'])
        with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
            # GH#22535
            result = rng - other
            tm.assert_index_equal(result, expected)

        with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
            # GH#22535
            result = other - rng
            tm.assert_index_equal(result, -expected) 
Example #30
Source File: test_arithmetic.py    From recruit with Apache License 2.0 5 votes vote down vote up
def test_tdi_sub_int(self, one):
        rng = timedelta_range('1 days 09:00:00', freq='H', periods=10)
        with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
            # GH#22535
            result = rng - one
        expected = timedelta_range('1 days 08:00:00', freq='H', periods=10)
        tm.assert_index_equal(result, expected)