Python pandas.util.testing.assert_raises_regex() Examples

The following are 30 code examples of pandas.util.testing.assert_raises_regex(). 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_window.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_no_pairwise_with_other(self, f):

        # DataFrame with another DataFrame, pairwise=False
        results = [f(df, self.df2) if df.columns.is_unique else None
                   for df in self.df1s]
        for (df, result) in zip(self.df1s, results):
            if result is not None:
                with catch_warnings(record=True):
                    # we can have int and str columns
                    expected_index = df.index.union(self.df2.index)
                    expected_columns = df.columns.union(self.df2.columns)
                tm.assert_index_equal(result.index, expected_index)
                tm.assert_index_equal(result.columns, expected_columns)
            else:
                tm.assert_raises_regex(
                    ValueError, "'arg1' columns are not unique", f, df,
                    self.df2)
                tm.assert_raises_regex(
                    ValueError, "'arg2' columns are not unique", f,
                    self.df2, df) 
Example #2
Source File: test_timedelta_range.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_errors(self):
        # not enough params
        msg = ('Of the four parameters: start, end, periods, and freq, '
               'exactly three must be specified')
        with tm.assert_raises_regex(ValueError, msg):
            timedelta_range(start='0 days')

        with tm.assert_raises_regex(ValueError, msg):
            timedelta_range(end='5 days')

        with tm.assert_raises_regex(ValueError, msg):
            timedelta_range(periods=2)

        with tm.assert_raises_regex(ValueError, msg):
            timedelta_range()

        # too many params
        with tm.assert_raises_regex(ValueError, msg):
            timedelta_range(start='0 days', end='5 days', periods=10, freq='H') 
Example #3
Source File: test_indexing.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_take_invalid_kwargs(self):
        idx = timedelta_range('1 day', '31 day', freq='D', name='idx')
        indices = [1, 6, 5, 9, 10, 13, 15, 3]

        msg = r"take\(\) got an unexpected keyword argument 'foo'"
        tm.assert_raises_regex(TypeError, msg, idx.take,
                               indices, foo=2)

        msg = "the 'out' parameter is not supported"
        tm.assert_raises_regex(ValueError, msg, idx.take,
                               indices, out=indices)

        msg = "the 'mode' parameter is not supported"
        tm.assert_raises_regex(ValueError, msg, idx.take,
                               indices, mode='clip')

    # TODO: This method came from test_timedelta; de-dup with version above 
Example #4
Source File: test_scalar_compat.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_tdi_round(self):
        td = pd.timedelta_range(start='16801 days', periods=5, freq='30Min')
        elt = td[1]

        expected_rng = TimedeltaIndex([Timedelta('16801 days 00:00:00'),
                                       Timedelta('16801 days 00:00:00'),
                                       Timedelta('16801 days 01:00:00'),
                                       Timedelta('16801 days 02:00:00'),
                                       Timedelta('16801 days 02:00:00')])
        expected_elt = expected_rng[1]

        tm.assert_index_equal(td.round(freq='H'), expected_rng)
        assert elt.round(freq='H') == expected_elt

        msg = pd._libs.tslibs.frequencies._INVALID_FREQ_ERROR
        with tm.assert_raises_regex(ValueError, msg):
            td.round(freq='foo')
        with tm.assert_raises_regex(ValueError, msg):
            elt.round(freq='foo')

        msg = "<MonthEnd> is a non-fixed frequency"
        with tm.assert_raises_regex(ValueError, msg):
            td.round(freq='M')
        with tm.assert_raises_regex(ValueError, msg):
            elt.round(freq='M') 
Example #5
Source File: test_panel.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_numpy_round(self):
        with catch_warnings(record=True):
            values = [[[-3.2, 2.2], [0, -4.8213], [3.123, 123.12],
                       [-1566.213, 88.88], [-12, 94.5]],
                      [[-5.82, 3.5], [6.21, -73.272], [-9.087, 23.12],
                       [272.212, -99.99], [23, -76.5]]]
            evalues = [[[float(np.around(i)) for i in j] for j in k]
                       for k in values]
            p = Panel(values, items=['Item1', 'Item2'],
                      major_axis=date_range('1/1/2000', periods=5),
                      minor_axis=['A', 'B'])
            expected = Panel(evalues, items=['Item1', 'Item2'],
                             major_axis=date_range('1/1/2000', periods=5),
                             minor_axis=['A', 'B'])
            result = np.round(p)
            assert_panel_equal(expected, result)

            msg = "the 'out' parameter is not supported"
            tm.assert_raises_regex(ValueError, msg, np.round, p, out=p) 
Example #6
Source File: test_ops.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_freq_setter_errors(self):
        # GH 20678
        idx = TimedeltaIndex(['0 days', '2 days', '4 days'])

        # setting with an incompatible freq
        msg = ('Inferred frequency 2D from passed values does not conform to '
               'passed frequency 5D')
        with tm.assert_raises_regex(ValueError, msg):
            idx.freq = '5D'

        # setting with a non-fixed frequency
        msg = '<2 \* BusinessDays> is a non-fixed frequency'
        with tm.assert_raises_regex(ValueError, msg):
            idx.freq = '2B'

        # setting with non-freq string
        with tm.assert_raises_regex(ValueError, 'Invalid frequency'):
            idx.freq = 'foo' 
Example #7
Source File: test_array.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_astype(self):
        res = self.arr.astype('f8')
        res.sp_values[:3] = 27
        assert not (self.arr.sp_values[:3] == 27).any()

        msg = "unable to coerce current fill_value nan to int64 dtype"
        with tm.assert_raises_regex(ValueError, msg):
            self.arr.astype('i8')

        arr = SparseArray([0, np.nan, 0, 1])
        with tm.assert_raises_regex(ValueError, msg):
            arr.astype('i8')

        arr = SparseArray([0, np.nan, 0, 1], fill_value=0)
        msg = 'Cannot convert non-finite values \\(NA or inf\\) to integer'
        with tm.assert_raises_regex(ValueError, msg):
            arr.astype('i8') 
Example #8
Source File: test_array.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_numpy_all(self, data, pos, neg):
        # GH 17570
        out = np.all(SparseArray(data))
        assert out

        out = np.all(SparseArray(data, fill_value=pos))
        assert out

        data[1] = neg
        out = np.all(SparseArray(data))
        assert not out

        out = np.all(SparseArray(data, fill_value=pos))
        assert not out

        msg = "the 'out' parameter is not supported"
        tm.assert_raises_regex(ValueError, msg, np.all,
                               SparseArray(data), out=out) 
Example #9
Source File: test_panel.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_set_value(self):
        with catch_warnings(record=True):
            for item in self.panel.items:
                for mjr in self.panel.major_axis[::2]:
                    for mnr in self.panel.minor_axis:
                        self.panel.set_value(item, mjr, mnr, 1.)
                        tm.assert_almost_equal(self.panel[item][mnr][mjr], 1.)

            # resize
            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 tm.assert_raises_regex(TypeError, msg):
                self.panel.set_value('a') 
Example #10
Source File: test_array.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_numpy_any(self, data, pos, neg):
        # GH 17570
        out = np.any(SparseArray(data))
        assert out

        out = np.any(SparseArray(data, fill_value=pos))
        assert out

        data[1] = neg
        out = np.any(SparseArray(data))
        assert not out

        out = np.any(SparseArray(data, fill_value=pos))
        assert not out

        msg = "the 'out' parameter is not supported"
        tm.assert_raises_regex(ValueError, msg, np.any,
                               SparseArray(data), out=out) 
Example #11
Source File: test_array.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_numpy_sum(self):
        data = np.arange(10).astype(float)
        out = np.sum(SparseArray(data))
        assert out == 45.0

        data[5] = np.nan
        out = np.sum(SparseArray(data, fill_value=2))
        assert out == 40.0

        out = np.sum(SparseArray(data, fill_value=np.nan))
        assert out == 40.0

        msg = "the 'dtype' parameter is not supported"
        tm.assert_raises_regex(ValueError, msg, np.sum,
                               SparseArray(data), dtype=np.int64)

        msg = "the 'out' parameter is not supported"
        tm.assert_raises_regex(ValueError, msg, np.sum,
                               SparseArray(data), out=out) 
Example #12
Source File: test_multi.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_metadata_immutable(self):
        levels, labels = self.index.levels, self.index.labels
        # shouldn't be able to set at either the top level or base level
        mutable_regex = re.compile('does not support mutable operations')
        with tm.assert_raises_regex(TypeError, mutable_regex):
            levels[0] = levels[0]
        with tm.assert_raises_regex(TypeError, mutable_regex):
            levels[0][0] = levels[0][0]
        # ditto for labels
        with tm.assert_raises_regex(TypeError, mutable_regex):
            labels[0] = labels[0]
        with tm.assert_raises_regex(TypeError, mutable_regex):
            labels[0][0] = labels[0][0]
        # and for names
        names = self.index.names
        with tm.assert_raises_regex(TypeError, mutable_regex):
            names[0] = names[0] 
Example #13
Source File: test_window.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_numpy_compat(self, method):
        # see gh-12811
        e = rwindow.EWM(Series([2, 4, 6]), alpha=0.5)

        msg = "numpy operations are not valid with window objects"

        tm.assert_raises_regex(UnsupportedFunctionCall, msg,
                               getattr(e, method), 1, 2, 3)
        tm.assert_raises_regex(UnsupportedFunctionCall, msg,
                               getattr(e, method), dtype=np.float64)


# gh-12373 : rolling functions error on float32 data
# make sure rolling functions works for different dtypes
#
# NOTE that these are yielded tests and so _create_data
# is explicitly called.
#
# further note that we are only checking rolling for fully dtype
# compliance (though both expanding and ewm inherit) 
Example #14
Source File: test_array.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_cumsum(self):
        non_null_data = np.array([1, 2, 3, 4, 5], dtype=float)
        non_null_expected = SparseArray(non_null_data.cumsum())

        null_data = np.array([1, 2, np.nan, 4, 5], dtype=float)
        null_expected = SparseArray(np.array([1.0, 3.0, np.nan, 7.0, 12.0]))

        for data, expected in [
            (null_data, null_expected),
            (non_null_data, non_null_expected)
        ]:
            out = SparseArray(data).cumsum()
            tm.assert_sp_array_equal(out, expected)

            out = SparseArray(data, fill_value=np.nan).cumsum()
            tm.assert_sp_array_equal(out, expected)

            out = SparseArray(data, fill_value=2).cumsum()
            tm.assert_sp_array_equal(out, expected)

            axis = 1  # SparseArray currently 1-D, so only axis = 0 is valid.
            msg = "axis\\(={axis}\\) out of bounds".format(axis=axis)
            with tm.assert_raises_regex(ValueError, msg):
                SparseArray(data).cumsum(axis=axis) 
Example #15
Source File: test_internals.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_unbounded_slice_raises(self):
        def assert_unbounded_slice_error(slc):
            tm.assert_raises_regex(ValueError, "unbounded slice",
                                   lambda: BlockPlacement(slc))

        assert_unbounded_slice_error(slice(None, None))
        assert_unbounded_slice_error(slice(10, None))
        assert_unbounded_slice_error(slice(None, None, -1))
        assert_unbounded_slice_error(slice(None, 10, -1))

        # These are "unbounded" because negative index will change depending on
        # container shape.
        assert_unbounded_slice_error(slice(-1, None))
        assert_unbounded_slice_error(slice(None, -1))
        assert_unbounded_slice_error(slice(-1, -1))
        assert_unbounded_slice_error(slice(-1, None, -1))
        assert_unbounded_slice_error(slice(None, -1, -1))
        assert_unbounded_slice_error(slice(-1, -1, -1)) 
Example #16
Source File: test_frame.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_constructor_ndarray(self):
        # no index or columns
        sp = SparseDataFrame(self.frame.values)

        # 1d
        sp = SparseDataFrame(self.data['A'], index=self.dates, columns=['A'])
        tm.assert_sp_frame_equal(sp, self.frame.reindex(columns=['A']))

        # raise on level argument
        pytest.raises(TypeError, self.frame.reindex, columns=['A'],
                      level=1)

        # wrong length index / columns
        with tm.assert_raises_regex(ValueError, "^Index length"):
            SparseDataFrame(self.frame.values, index=self.frame.index[:-1])

        with tm.assert_raises_regex(ValueError, "^Column length"):
            SparseDataFrame(self.frame.values, columns=self.frame.columns[:-1])

    # GH 9272 
Example #17
Source File: test_multi.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_constructor_mismatched_label_levels(self):
        labels = [np.array([1]), np.array([2]), np.array([3])]
        levels = ["a"]
        tm.assert_raises_regex(ValueError, "Length of levels and labels "
                                           "must be the same", MultiIndex,
                               levels=levels, labels=labels)
        length_error = re.compile('>= length of level')
        label_error = re.compile(r'Unequal label lengths: \[4, 2\]')

        # important to check that it's looking at the right thing.
        with tm.assert_raises_regex(ValueError, length_error):
            MultiIndex(levels=[['a'], ['b']],
                       labels=[[0, 1, 2, 3], [0, 3, 4, 1]])

        with tm.assert_raises_regex(ValueError, label_error):
            MultiIndex(levels=[['a'], ['b']], labels=[[0, 0, 0, 0], [0, 0]])

        # external API
        with tm.assert_raises_regex(ValueError, length_error):
            self.index.copy().set_levels([['a'], ['b']])

        with tm.assert_raises_regex(ValueError, label_error):
            self.index.copy().set_labels([[0, 0, 0, 0], [0, 0]]) 
Example #18
Source File: test_multi.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_constructor_nonhashable_names(self):
        # GH 20527
        levels = [[1, 2], [u'one', u'two']]
        labels = [[0, 0, 1, 1], [0, 1, 0, 1]]
        names = ((['foo'], ['bar']))
        message = "MultiIndex.name must be a hashable type"
        tm.assert_raises_regex(TypeError, message,
                               MultiIndex, levels=levels,
                               labels=labels, names=names)

        # With .rename()
        mi = MultiIndex(levels=[[1, 2], [u'one', u'two']],
                        labels=[[0, 0, 1, 1], [0, 1, 0, 1]],
                        names=('foo', 'bar'))
        renamed = [['foor'], ['barr']]
        tm.assert_raises_regex(TypeError, message, mi.rename, names=renamed)
        # With .set_names()
        tm.assert_raises_regex(TypeError, message, mi.set_names, names=renamed) 
Example #19
Source File: test_series.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_numpy_cumsum(self):
        result = np.cumsum(self.bseries)
        expected = SparseSeries(self.bseries.to_dense().cumsum())
        tm.assert_sp_series_equal(result, expected)

        result = np.cumsum(self.zbseries)
        expected = self.zbseries.to_dense().cumsum()
        tm.assert_series_equal(result, expected)

        msg = "the 'dtype' parameter is not supported"
        tm.assert_raises_regex(ValueError, msg, np.cumsum,
                               self.bseries, dtype=np.int64)

        msg = "the 'out' parameter is not supported"
        tm.assert_raises_regex(ValueError, msg, np.cumsum,
                               self.zbseries, out=result) 
Example #20
Source File: test_multi.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_from_arrays_empty(self):
        # 0 levels
        with tm.assert_raises_regex(
                ValueError, "Must pass non-zero number of levels/labels"):
            MultiIndex.from_arrays(arrays=[])

        # 1 level
        result = MultiIndex.from_arrays(arrays=[[]], names=['A'])
        assert isinstance(result, MultiIndex)
        expected = Index([], name='A')
        tm.assert_index_equal(result.levels[0], expected)

        # N levels
        for N in [2, 3]:
            arrays = [[]] * N
            names = list('ABC')[:N]
            result = MultiIndex.from_arrays(arrays=arrays, names=names)
            expected = MultiIndex(levels=[[]] * N, labels=[[]] * N,
                                  names=names)
            tm.assert_index_equal(result, expected) 
Example #21
Source File: test_multi.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_from_arrays_different_lengths(self):
        # see gh-13599
        idx1 = [1, 2, 3]
        idx2 = ['a', 'b']
        tm.assert_raises_regex(ValueError, '^all arrays must '
                                           'be same length$',
                               MultiIndex.from_arrays, [idx1, idx2])

        idx1 = []
        idx2 = ['a', 'b']
        tm.assert_raises_regex(ValueError, '^all arrays must '
                                           'be same length$',
                               MultiIndex.from_arrays, [idx1, idx2])

        idx1 = [1, 2, 3]
        idx2 = []
        tm.assert_raises_regex(ValueError, '^all arrays must '
                                           'be same length$',
                               MultiIndex.from_arrays, [idx1, idx2]) 
Example #22
Source File: test_multi.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_from_product_iterator(self):
        # GH 18434
        first = ['foo', 'bar', 'buz']
        second = ['a', 'b', 'c']
        names = ['first', 'second']
        tuples = [('foo', 'a'), ('foo', 'b'), ('foo', 'c'), ('bar', 'a'),
                  ('bar', 'b'), ('bar', 'c'), ('buz', 'a'), ('buz', 'b'),
                  ('buz', 'c')]
        expected = MultiIndex.from_tuples(tuples, names=names)

        # iterator as input
        result = MultiIndex.from_product(iter([first, second]), names=names)
        tm.assert_index_equal(result, expected)

        # Invalid non-iterable input
        with tm.assert_raises_regex(
                TypeError, "Input must be a list / sequence of iterables."):
            MultiIndex.from_product(0) 
Example #23
Source File: test_multi.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_names(self):

        # names are assigned in setup
        names = self.index_names
        level_names = [level.name for level in self.index.levels]
        assert names == level_names

        # setting bad names on existing
        index = self.index
        tm.assert_raises_regex(ValueError, "^Length of names",
                               setattr, index, "names",
                               list(index.names) + ["third"])
        tm.assert_raises_regex(ValueError, "^Length of names",
                               setattr, index, "names", [])

        # initializing with bad names (should always be equivalent)
        major_axis, minor_axis = self.index.levels
        major_labels, minor_labels = self.index.labels
        tm.assert_raises_regex(ValueError, "^Length of names", MultiIndex,
                               levels=[major_axis, minor_axis],
                               labels=[major_labels, minor_labels],
                               names=['first'])
        tm.assert_raises_regex(ValueError, "^Length of names", MultiIndex,
                               levels=[major_axis, minor_axis],
                               labels=[major_labels, minor_labels],
                               names=['first', 'second', 'third'])

        # names are assigned
        index.names = ["a", "b"]
        ind_names = list(index.names)
        level_names = [level.name for level in index.levels]
        assert ind_names == level_names 
Example #24
Source File: test_indexing.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_get_loc(self):
        idx = pd.to_timedelta(['0 days', '1 days', '2 days'])

        for method in [None, 'pad', 'backfill', 'nearest']:
            assert idx.get_loc(idx[1], method) == 1
            assert idx.get_loc(idx[1].to_pytimedelta(), method) == 1
            assert idx.get_loc(str(idx[1]), method) == 1

        assert idx.get_loc(idx[1], 'pad',
                           tolerance=Timedelta(0)) == 1
        assert idx.get_loc(idx[1], 'pad',
                           tolerance=np.timedelta64(0, 's')) == 1
        assert idx.get_loc(idx[1], 'pad',
                           tolerance=timedelta(0)) == 1

        with tm.assert_raises_regex(ValueError,
                                    'unit abbreviation w/o a number'):
            idx.get_loc(idx[1], method='nearest', tolerance='foo')

        with pytest.raises(
                ValueError,
                match='tolerance size must match'):
            idx.get_loc(idx[1], method='nearest',
                        tolerance=[Timedelta(0).to_timedelta64(),
                                   Timedelta(0).to_timedelta64()])

        for method, loc in [('pad', 1), ('backfill', 2), ('nearest', 1)]:
            assert idx.get_loc('1 day 1 hour', method) == loc

        # GH 16909
        assert idx.get_loc(idx[1].to_timedelta64()) == 1

        # GH 16896
        assert idx.get_loc('0 days') == 0 
Example #25
Source File: test_indexing.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_take_fill_value(self):
        # GH 12631
        idx = TimedeltaIndex(['1 days', '2 days', '3 days'],
                             name='xxx')
        result = idx.take(np.array([1, 0, -1]))
        expected = TimedeltaIndex(['2 days', '1 days', '3 days'],
                                  name='xxx')
        tm.assert_index_equal(result, expected)

        # fill_value
        result = idx.take(np.array([1, 0, -1]), fill_value=True)
        expected = TimedeltaIndex(['2 days', '1 days', 'NaT'],
                                  name='xxx')
        tm.assert_index_equal(result, expected)

        # allow_fill=False
        result = idx.take(np.array([1, 0, -1]), allow_fill=False,
                          fill_value=True)
        expected = TimedeltaIndex(['2 days', '1 days', '3 days'],
                                  name='xxx')
        tm.assert_index_equal(result, expected)

        msg = ('When allow_fill=True and fill_value is not None, '
               'all indices must be >= -1')
        with tm.assert_raises_regex(ValueError, msg):
            idx.take(np.array([1, 0, -2]), fill_value=True)
        with tm.assert_raises_regex(ValueError, msg):
            idx.take(np.array([1, 0, -5]), fill_value=True)

        with pytest.raises(IndexError):
            idx.take(np.array([1, -5])) 
Example #26
Source File: test_libsparse.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_check_integrity(self):

        # Too many indices than specified in self.length
        msg = "Too many indices"

        with tm.assert_raises_regex(ValueError, msg):
            IntIndex(length=1, indices=[1, 2, 3])

        # No index can be negative.
        msg = "No index can be less than zero"

        with tm.assert_raises_regex(ValueError, msg):
            IntIndex(length=5, indices=[1, -2, 3])

        # No index can be negative.
        msg = "No index can be less than zero"

        with tm.assert_raises_regex(ValueError, msg):
            IntIndex(length=5, indices=[1, -2, 3])

        # All indices must be less than the length.
        msg = "All indices must be less than the length"

        with tm.assert_raises_regex(ValueError, msg):
            IntIndex(length=5, indices=[1, 2, 5])

        with tm.assert_raises_regex(ValueError, msg):
            IntIndex(length=5, indices=[1, 2, 6])

        # Indices must be strictly ascending.
        msg = "Indices must be strictly increasing"

        with tm.assert_raises_regex(ValueError, msg):
            IntIndex(length=5, indices=[1, 3, 2])

        with tm.assert_raises_regex(ValueError, msg):
            IntIndex(length=5, indices=[1, 3, 3]) 
Example #27
Source File: test_internals.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_validate_ndim():
    values = np.array([1.0, 2.0])
    placement = slice(2)
    msg = "Wrong number of dimensions. values.ndim != ndim \[1 != 2\]"

    with tm.assert_raises_regex(ValueError, msg):
        make_block(values, placement, ndim=2) 
Example #28
Source File: test_resample.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_fails_on_no_datetime_index(self):
        index_names = ('Int64Index', 'Index', 'Float64Index', 'MultiIndex')
        index_funcs = (tm.makeIntIndex,
                       tm.makeUnicodeIndex, tm.makeFloatIndex,
                       lambda m: tm.makeCustomIndex(m, 2))
        n = 2
        for name, func in zip(index_names, index_funcs):
            index = func(n)
            df = DataFrame({'a': np.random.randn(n)}, index=index)
            with tm.assert_raises_regex(TypeError,
                                        "Only valid with "
                                        "DatetimeIndex, TimedeltaIndex "
                                        "or PeriodIndex, but got an "
                                        "instance of %r" % name):
                df.groupby(TimeGrouper('D')) 
Example #29
Source File: test_resample.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_numpy_compat(self):
        # see gh-12811
        s = Series([1, 2, 3, 4, 5], index=date_range(
            '20130101', periods=5, freq='s'))
        r = s.resample('2s')

        msg = "numpy operations are not valid with resample"

        for func in ('min', 'max', 'sum', 'prod',
                     'mean', 'var', 'std'):
            tm.assert_raises_regex(UnsupportedFunctionCall, msg,
                                   getattr(r, func),
                                   func, 1, 2, 3)
            tm.assert_raises_regex(UnsupportedFunctionCall, msg,
                                   getattr(r, func), axis=1) 
Example #30
Source File: test_array.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_numpy_cumsum(self):
        non_null_data = np.array([1, 2, 3, 4, 5], dtype=float)
        non_null_expected = SparseArray(non_null_data.cumsum())

        null_data = np.array([1, 2, np.nan, 4, 5], dtype=float)
        null_expected = SparseArray(np.array([1.0, 3.0, np.nan, 7.0, 12.0]))

        for data, expected in [
            (null_data, null_expected),
            (non_null_data, non_null_expected)
        ]:
            out = np.cumsum(SparseArray(data))
            tm.assert_sp_array_equal(out, expected)

            out = np.cumsum(SparseArray(data, fill_value=np.nan))
            tm.assert_sp_array_equal(out, expected)

            out = np.cumsum(SparseArray(data, fill_value=2))
            tm.assert_sp_array_equal(out, expected)

            msg = "the 'dtype' parameter is not supported"
            tm.assert_raises_regex(ValueError, msg, np.cumsum,
                                   SparseArray(data), dtype=np.int64)

            msg = "the 'out' parameter is not supported"
            tm.assert_raises_regex(ValueError, msg, np.cumsum,
                                   SparseArray(data), out=out)