Python pandas.IndexSlice() Examples

The following are 30 code examples of pandas.IndexSlice(). 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 , or try the search function .
Example #1
Source File: test_partial_slicing.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def test_slice_with_negative_step(self):
        ts = Series(np.arange(20),
                    period_range('2014-01', periods=20, freq='M'))
        SLC = pd.IndexSlice

        def assert_slices_equivalent(l_slc, i_slc):
            tm.assert_series_equal(ts[l_slc], ts.iloc[i_slc])
            tm.assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc])
            tm.assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc])

        assert_slices_equivalent(SLC[Period('2014-10')::-1], SLC[9::-1])
        assert_slices_equivalent(SLC['2014-10'::-1], SLC[9::-1])

        assert_slices_equivalent(SLC[:Period('2014-10'):-1], SLC[:8:-1])
        assert_slices_equivalent(SLC[:'2014-10':-1], SLC[:8:-1])

        assert_slices_equivalent(SLC['2015-02':'2014-10':-1], SLC[13:8:-1])
        assert_slices_equivalent(SLC[Period('2015-02'):Period('2014-10'):-1],
                                 SLC[13:8:-1])
        assert_slices_equivalent(SLC['2015-02':Period('2014-10'):-1],
                                 SLC[13:8:-1])
        assert_slices_equivalent(SLC[Period('2015-02'):'2014-10':-1],
                                 SLC[13:8:-1])

        assert_slices_equivalent(SLC['2014-10':'2015-02':-1], SLC[:0]) 
Example #2
Source File: test_style.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def test_where_subset(self):
        # GH 17474
        def f(x):
            return x > 0.5

        style1 = 'foo: bar'
        style2 = 'baz: foo'

        slices = [pd.IndexSlice[:], pd.IndexSlice[:, ['A']],
                  pd.IndexSlice[[1], :], pd.IndexSlice[[1], ['A']],
                  pd.IndexSlice[:2, ['A', 'B']]]

        for slice_ in slices:
            result = self.df.style.where(f, style1, style2,
                                         subset=slice_)._compute().ctx
            expected = {(r, c):
                        [style1 if f(self.df.loc[row, col]) else style2]
                        for r, row in enumerate(self.df.index)
                        for c, col in enumerate(self.df.columns)
                        if row in self.df.loc[slice_].index and
                        col in self.df.loc[slice_].columns}
            assert result == expected 
Example #3
Source File: test_slice.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_non_reducing_slice_on_multiindex(self):
        # GH 19861
        dic = {
            ('a', 'd'): [1, 4],
            ('a', 'c'): [2, 3],
            ('b', 'c'): [3, 2],
            ('b', 'd'): [4, 1]
        }
        df = pd.DataFrame(dic, index=[0, 1])
        idx = pd.IndexSlice
        slice_ = idx[:, idx['b', 'd']]
        tslice_ = _non_reducing_slice(slice_)

        result = df.loc[tslice_]
        expected = pd.DataFrame({('b', 'd'): [4, 1]})
        tm.assert_frame_equal(result, expected) 
Example #4
Source File: test_style.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def test_bad_apply_shape(self):
        df = pd.DataFrame([[1, 2], [3, 4]])
        with pytest.raises(ValueError):
            df.style._apply(lambda x: 'x', subset=pd.IndexSlice[[0, 1], :])

        with pytest.raises(ValueError):
            df.style._apply(lambda x: [''], subset=pd.IndexSlice[[0, 1], :])

        with pytest.raises(ValueError):
            df.style._apply(lambda x: ['', '', '', ''])

        with pytest.raises(ValueError):
            df.style._apply(lambda x: ['', '', ''], subset=1)

        with pytest.raises(ValueError):
            df.style._apply(lambda x: ['', '', ''], axis=1) 
Example #5
Source File: test_style.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def test_where_subset_compare_with_applymap(self):
        # GH 17474
        def f(x):
            return x > 0.5

        style1 = 'foo: bar'
        style2 = 'baz: foo'

        def g(x):
            return style1 if f(x) else style2

        slices = [pd.IndexSlice[:], pd.IndexSlice[:, ['A']],
                  pd.IndexSlice[[1], :], pd.IndexSlice[[1], ['A']],
                  pd.IndexSlice[:2, ['A', 'B']]]

        for slice_ in slices:
            result = self.df.style.where(f, style1, style2,
                                         subset=slice_)._compute().ctx
            expected = self.df.style.applymap(g, subset=slice_)._compute().ctx
            assert result == expected 
Example #6
Source File: test_style.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_applymap_subset(self):
        def f(x):
            return 'foo: bar'

        slices = [pd.IndexSlice[:], pd.IndexSlice[:, ['A']],
                  pd.IndexSlice[[1], :], pd.IndexSlice[[1], ['A']],
                  pd.IndexSlice[:2, ['A', 'B']]]

        for slice_ in slices:
            result = self.df.style.applymap(f, subset=slice_)._compute().ctx
            expected = dict(((r, c), ['foo: bar'])
                            for r, row in enumerate(self.df.index)
                            for c, col in enumerate(self.df.columns)
                            if row in self.df.loc[slice_].index and
                            col in self.df.loc[slice_].columns)
            assert result == expected 
Example #7
Source File: test_style.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def test_applymap_subset(self):
        def f(x):
            return 'foo: bar'

        slices = [pd.IndexSlice[:], pd.IndexSlice[:, ['A']],
                  pd.IndexSlice[[1], :], pd.IndexSlice[[1], ['A']],
                  pd.IndexSlice[:2, ['A', 'B']]]

        for slice_ in slices:
            result = self.df.style.applymap(f, subset=slice_)._compute().ctx
            expected = {(r, c): ['foo: bar']
                        for r, row in enumerate(self.df.index)
                        for c, col in enumerate(self.df.columns)
                        if row in self.df.loc[slice_].index and
                        col in self.df.loc[slice_].columns}
            assert result == expected 
Example #8
Source File: test_style.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_bad_apply_shape(self):
        df = pd.DataFrame([[1, 2], [3, 4]])
        with pytest.raises(ValueError):
            df.style._apply(lambda x: 'x', subset=pd.IndexSlice[[0, 1], :])

        with pytest.raises(ValueError):
            df.style._apply(lambda x: [''], subset=pd.IndexSlice[[0, 1], :])

        with pytest.raises(ValueError):
            df.style._apply(lambda x: ['', '', '', ''])

        with pytest.raises(ValueError):
            df.style._apply(lambda x: ['', '', ''], subset=1)

        with pytest.raises(ValueError):
            df.style._apply(lambda x: ['', '', ''], axis=1) 
Example #9
Source File: test_indexing.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_str_label_slicing_with_negative_step(self):
        SLC = pd.IndexSlice

        def assert_slices_equivalent(l_slc, i_slc):
            tm.assert_series_equal(s.loc[l_slc], s.iloc[i_slc])

            if not idx.is_integer:
                # For integer indices, ix and plain getitem are position-based.
                tm.assert_series_equal(s[l_slc], s.iloc[i_slc])
                tm.assert_series_equal(s.loc[l_slc], s.iloc[i_slc])

        for idx in [_mklbl('A', 20), np.arange(20) + 100,
                    np.linspace(100, 150, 20)]:
            idx = Index(idx)
            s = Series(np.arange(20), index=idx)
            assert_slices_equivalent(SLC[idx[9]::-1], SLC[9::-1])
            assert_slices_equivalent(SLC[:idx[9]:-1], SLC[:8:-1])
            assert_slices_equivalent(SLC[idx[13]:idx[9]:-1], SLC[13:8:-1])
            assert_slices_equivalent(SLC[idx[9]:idx[13]:-1], SLC[:0]) 
Example #10
Source File: test_partial_slicing.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_slice_with_negative_step(self):
        ts = Series(np.arange(20),
                    period_range('2014-01', periods=20, freq='M'))
        SLC = pd.IndexSlice

        def assert_slices_equivalent(l_slc, i_slc):
            tm.assert_series_equal(ts[l_slc], ts.iloc[i_slc])
            tm.assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc])
            tm.assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc])

        assert_slices_equivalent(SLC[Period('2014-10')::-1], SLC[9::-1])
        assert_slices_equivalent(SLC['2014-10'::-1], SLC[9::-1])

        assert_slices_equivalent(SLC[:Period('2014-10'):-1], SLC[:8:-1])
        assert_slices_equivalent(SLC[:'2014-10':-1], SLC[:8:-1])

        assert_slices_equivalent(SLC['2015-02':'2014-10':-1], SLC[13:8:-1])
        assert_slices_equivalent(SLC[Period('2015-02'):Period('2014-10'):-1],
                                 SLC[13:8:-1])
        assert_slices_equivalent(SLC['2015-02':Period('2014-10'):-1],
                                 SLC[13:8:-1])
        assert_slices_equivalent(SLC[Period('2015-02'):'2014-10':-1],
                                 SLC[13:8:-1])

        assert_slices_equivalent(SLC['2014-10':'2015-02':-1], SLC[:0]) 
Example #11
Source File: style.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def hide_columns(self, subset):
        """
        Hide columns from rendering.

        .. versionadded:: 0.23.0

        Parameters
        ----------
        subset : IndexSlice
            An argument to ``DataFrame.loc`` that identifies which columns
            are hidden.

        Returns
        -------
        self : Styler
        """
        subset = _non_reducing_slice(subset)
        hidden_df = self.data.loc[subset]
        self.hidden_columns = self.columns.get_indexer_for(hidden_df.columns)
        return self

    # -----------------------------------------------------------------------
    # A collection of "builtin" styles
    # ----------------------------------------------------------------------- 
Example #12
Source File: test_partial_slicing.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_slice_with_negative_step(self):
        ts = Series(np.arange(20), timedelta_range('0', periods=20, freq='H'))
        SLC = pd.IndexSlice

        def assert_slices_equivalent(l_slc, i_slc):
            assert_series_equal(ts[l_slc], ts.iloc[i_slc])
            assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc])
            assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc])

        assert_slices_equivalent(SLC[Timedelta(hours=7)::-1], SLC[7::-1])
        assert_slices_equivalent(SLC['7 hours'::-1], SLC[7::-1])

        assert_slices_equivalent(SLC[:Timedelta(hours=7):-1], SLC[:6:-1])
        assert_slices_equivalent(SLC[:'7 hours':-1], SLC[:6:-1])

        assert_slices_equivalent(SLC['15 hours':'7 hours':-1], SLC[15:6:-1])
        assert_slices_equivalent(SLC[Timedelta(hours=15):Timedelta(hours=7):-
                                     1], SLC[15:6:-1])
        assert_slices_equivalent(SLC['15 hours':Timedelta(hours=7):-1],
                                 SLC[15:6:-1])
        assert_slices_equivalent(SLC[Timedelta(hours=15):'7 hours':-1],
                                 SLC[15:6:-1])

        assert_slices_equivalent(SLC['7 hours':'15 hours':-1], SLC[:0]) 
Example #13
Source File: helpers.py    From quail with MIT License 6 votes vote down vote up
def df2list(df):
    """
    Convert a MultiIndex df to list

    Parameters
    ----------

    df : pandas.DataFrame
        A MultiIndex DataFrame where the first level is subjects and the second
        level is lists (e.g. egg.pres)

    Returns
    ----------

    lst : a list of lists of lists of values
        The input df reformatted as a list

    """
    subjects = df.index.levels[0].values.tolist()
    lists = df.index.levels[1].values.tolist()
    idx = pd.IndexSlice
    df = df.loc[idx[subjects,lists],df.columns]
    lst = [df.loc[sub,:].values.tolist() for sub in subjects]
    return lst 
Example #14
Source File: test_style.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_where_subset(self):
        # GH 17474
        def f(x):
            return x > 0.5

        style1 = 'foo: bar'
        style2 = 'baz: foo'

        slices = [pd.IndexSlice[:], pd.IndexSlice[:, ['A']],
                  pd.IndexSlice[[1], :], pd.IndexSlice[[1], ['A']],
                  pd.IndexSlice[:2, ['A', 'B']]]

        for slice_ in slices:
            result = self.df.style.where(f, style1, style2,
                                         subset=slice_)._compute().ctx
            expected = dict(((r, c),
                            [style1 if f(self.df.loc[row, col]) else style2])
                            for r, row in enumerate(self.df.index)
                            for c, col in enumerate(self.df.columns)
                            if row in self.df.loc[slice_].index and
                            col in self.df.loc[slice_].columns)
            assert result == expected 
Example #15
Source File: test_style.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_applymap_subset(self):
        def f(x):
            return 'foo: bar'

        slices = [pd.IndexSlice[:], pd.IndexSlice[:, ['A']],
                  pd.IndexSlice[[1], :], pd.IndexSlice[[1], ['A']],
                  pd.IndexSlice[:2, ['A', 'B']]]

        for slice_ in slices:
            result = self.df.style.applymap(f, subset=slice_)._compute().ctx
            expected = {(r, c): ['foo: bar']
                        for r, row in enumerate(self.df.index)
                        for c, col in enumerate(self.df.columns)
                        if row in self.df.loc[slice_].index and
                        col in self.df.loc[slice_].columns}
            assert result == expected 
Example #16
Source File: test_style.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_where_subset_compare_with_applymap(self):
        # GH 17474
        def f(x):
            return x > 0.5

        style1 = 'foo: bar'
        style2 = 'baz: foo'

        def g(x):
            return style1 if f(x) else style2

        slices = [pd.IndexSlice[:], pd.IndexSlice[:, ['A']],
                  pd.IndexSlice[[1], :], pd.IndexSlice[[1], ['A']],
                  pd.IndexSlice[:2, ['A', 'B']]]

        for slice_ in slices:
            result = self.df.style.where(f, style1, style2,
                                         subset=slice_)._compute().ctx
            expected = self.df.style.applymap(g, subset=slice_)._compute().ctx
            assert result == expected 
Example #17
Source File: style.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def hide_columns(self, subset):
        """
        Hide columns from rendering.

        .. versionadded:: 0.23.0

        Parameters
        ----------
        subset: IndexSlice
            An argument to ``DataFrame.loc`` that identifies which columns
            are hidden.

        Returns
        -------
        self : Styler
        """
        subset = _non_reducing_slice(subset)
        hidden_df = self.data.loc[subset]
        self.hidden_columns = self.columns.get_indexer_for(hidden_df.columns)
        return self

    # -----------------------------------------------------------------------
    # A collection of "builtin" styles
    # ----------------------------------------------------------------------- 
Example #18
Source File: test_style.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_bad_apply_shape(self):
        df = pd.DataFrame([[1, 2], [3, 4]])
        with pytest.raises(ValueError):
            df.style._apply(lambda x: 'x', subset=pd.IndexSlice[[0, 1], :])

        with pytest.raises(ValueError):
            df.style._apply(lambda x: [''], subset=pd.IndexSlice[[0, 1], :])

        with pytest.raises(ValueError):
            df.style._apply(lambda x: ['', '', '', ''])

        with pytest.raises(ValueError):
            df.style._apply(lambda x: ['', '', ''], subset=1)

        with pytest.raises(ValueError):
            df.style._apply(lambda x: ['', '', ''], axis=1) 
Example #19
Source File: test_slice.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def test_non_reducing_slice_on_multiindex(self):
        # GH 19861
        dic = {
            ('a', 'd'): [1, 4],
            ('a', 'c'): [2, 3],
            ('b', 'c'): [3, 2],
            ('b', 'd'): [4, 1]
        }
        df = pd.DataFrame(dic, index=[0, 1])
        idx = pd.IndexSlice
        slice_ = idx[:, idx['b', 'd']]
        tslice_ = _non_reducing_slice(slice_)

        result = df.loc[tslice_]
        expected = pd.DataFrame({('b', 'd'): [4, 1]})
        tm.assert_frame_equal(result, expected) 
Example #20
Source File: style.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def highlight_min(self, subset=None, color='yellow', axis=0):
        """
        Highlight the minimum by shading the background

        Parameters
        ----------
        subset: IndexSlice, default None
            a valid slice for ``data`` to limit the style application to
        color: str, default 'yellow'
        axis: int, str, or None; default 0
            0 or 'index' for columnwise (default), 1 or 'columns' for rowwise,
            or ``None`` for tablewise

        Returns
        -------
        self : Styler
        """
        return self._highlight_handler(subset=subset, color=color, axis=axis,
                                       max_=False) 
Example #21
Source File: style.py    From recruit with Apache License 2.0 6 votes vote down vote up
def hide_columns(self, subset):
        """
        Hide columns from rendering.

        .. versionadded:: 0.23.0

        Parameters
        ----------
        subset : IndexSlice
            An argument to ``DataFrame.loc`` that identifies which columns
            are hidden.

        Returns
        -------
        self : Styler
        """
        subset = _non_reducing_slice(subset)
        hidden_df = self.data.loc[subset]
        self.hidden_columns = self.columns.get_indexer_for(hidden_df.columns)
        return self

    # -----------------------------------------------------------------------
    # A collection of "builtin" styles
    # ----------------------------------------------------------------------- 
Example #22
Source File: test_partial_slicing.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def test_slice_with_negative_step(self):
        ts = Series(np.arange(20), timedelta_range('0', periods=20, freq='H'))
        SLC = pd.IndexSlice

        def assert_slices_equivalent(l_slc, i_slc):
            assert_series_equal(ts[l_slc], ts.iloc[i_slc])
            assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc])
            assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc])

        assert_slices_equivalent(SLC[Timedelta(hours=7)::-1], SLC[7::-1])
        assert_slices_equivalent(SLC['7 hours'::-1], SLC[7::-1])

        assert_slices_equivalent(SLC[:Timedelta(hours=7):-1], SLC[:6:-1])
        assert_slices_equivalent(SLC[:'7 hours':-1], SLC[:6:-1])

        assert_slices_equivalent(SLC['15 hours':'7 hours':-1], SLC[15:6:-1])
        assert_slices_equivalent(SLC[Timedelta(hours=15):Timedelta(hours=7):-
                                     1], SLC[15:6:-1])
        assert_slices_equivalent(SLC['15 hours':Timedelta(hours=7):-1],
                                 SLC[15:6:-1])
        assert_slices_equivalent(SLC[Timedelta(hours=15):'7 hours':-1],
                                 SLC[15:6:-1])

        assert_slices_equivalent(SLC['7 hours':'15 hours':-1], SLC[:0]) 
Example #23
Source File: style.py    From recruit with Apache License 2.0 6 votes vote down vote up
def highlight_max(self, subset=None, color='yellow', axis=0):
        """
        Highlight the maximum by shading the background.

        Parameters
        ----------
        subset : IndexSlice, default None
            a valid slice for ``data`` to limit the style application to
        color : str, default 'yellow'
        axis : int, str, or None; default 0
            0 or 'index' for columnwise (default), 1 or 'columns' for rowwise,
            or ``None`` for tablewise

        Returns
        -------
        self : Styler
        """
        return self._highlight_handler(subset=subset, color=color, axis=axis,
                                       max_=True) 
Example #24
Source File: style.py    From recruit with Apache License 2.0 6 votes vote down vote up
def highlight_min(self, subset=None, color='yellow', axis=0):
        """
        Highlight the minimum by shading the background.

        Parameters
        ----------
        subset : IndexSlice, default None
            a valid slice for ``data`` to limit the style application to
        color : str, default 'yellow'
        axis : int, str, or None; default 0
            0 or 'index' for columnwise (default), 1 or 'columns' for rowwise,
            or ``None`` for tablewise

        Returns
        -------
        self : Styler
        """
        return self._highlight_handler(subset=subset, color=color, axis=axis,
                                       max_=False) 
Example #25
Source File: test_partial_slicing.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_slice_with_negative_step(self):
        ts = Series(np.arange(20), timedelta_range('0', periods=20, freq='H'))
        SLC = pd.IndexSlice

        def assert_slices_equivalent(l_slc, i_slc):
            assert_series_equal(ts[l_slc], ts.iloc[i_slc])
            assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc])
            assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc])

        assert_slices_equivalent(SLC[Timedelta(hours=7)::-1], SLC[7::-1])
        assert_slices_equivalent(SLC['7 hours'::-1], SLC[7::-1])

        assert_slices_equivalent(SLC[:Timedelta(hours=7):-1], SLC[:6:-1])
        assert_slices_equivalent(SLC[:'7 hours':-1], SLC[:6:-1])

        assert_slices_equivalent(SLC['15 hours':'7 hours':-1], SLC[15:6:-1])
        assert_slices_equivalent(SLC[Timedelta(hours=15):Timedelta(hours=7):-
                                     1], SLC[15:6:-1])
        assert_slices_equivalent(SLC['15 hours':Timedelta(hours=7):-1],
                                 SLC[15:6:-1])
        assert_slices_equivalent(SLC[Timedelta(hours=15):'7 hours':-1],
                                 SLC[15:6:-1])

        assert_slices_equivalent(SLC['7 hours':'15 hours':-1], SLC[:0]) 
Example #26
Source File: test_partial_slicing.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_slice_with_negative_step(self):
        ts = Series(np.arange(20),
                    period_range('2014-01', periods=20, freq='M'))
        SLC = pd.IndexSlice

        def assert_slices_equivalent(l_slc, i_slc):
            tm.assert_series_equal(ts[l_slc], ts.iloc[i_slc])
            tm.assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc])
            tm.assert_series_equal(ts.loc[l_slc], ts.iloc[i_slc])

        assert_slices_equivalent(SLC[Period('2014-10')::-1], SLC[9::-1])
        assert_slices_equivalent(SLC['2014-10'::-1], SLC[9::-1])

        assert_slices_equivalent(SLC[:Period('2014-10'):-1], SLC[:8:-1])
        assert_slices_equivalent(SLC[:'2014-10':-1], SLC[:8:-1])

        assert_slices_equivalent(SLC['2015-02':'2014-10':-1], SLC[13:8:-1])
        assert_slices_equivalent(SLC[Period('2015-02'):Period('2014-10'):-1],
                                 SLC[13:8:-1])
        assert_slices_equivalent(SLC['2015-02':Period('2014-10'):-1],
                                 SLC[13:8:-1])
        assert_slices_equivalent(SLC[Period('2015-02'):'2014-10':-1],
                                 SLC[13:8:-1])

        assert_slices_equivalent(SLC['2014-10':'2015-02':-1], SLC[:0]) 
Example #27
Source File: test_indexing.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def test_str_label_slicing_with_negative_step(self):
        SLC = pd.IndexSlice

        def assert_slices_equivalent(l_slc, i_slc):
            tm.assert_series_equal(s.loc[l_slc], s.iloc[i_slc])

            if not idx.is_integer:
                # For integer indices, ix and plain getitem are position-based.
                tm.assert_series_equal(s[l_slc], s.iloc[i_slc])
                tm.assert_series_equal(s.loc[l_slc], s.iloc[i_slc])

        for idx in [_mklbl('A', 20), np.arange(20) + 100,
                    np.linspace(100, 150, 20)]:
            idx = Index(idx)
            s = Series(np.arange(20), index=idx)
            assert_slices_equivalent(SLC[idx[9]::-1], SLC[9::-1])
            assert_slices_equivalent(SLC[:idx[9]:-1], SLC[:8:-1])
            assert_slices_equivalent(SLC[idx[13]:idx[9]:-1], SLC[13:8:-1])
            assert_slices_equivalent(SLC[idx[9]:idx[13]:-1], SLC[:0]) 
Example #28
Source File: test_indexing.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_str_label_slicing_with_negative_step(self):
        SLC = pd.IndexSlice

        def assert_slices_equivalent(l_slc, i_slc):
            tm.assert_series_equal(s.loc[l_slc], s.iloc[i_slc])

            if not idx.is_integer:
                # For integer indices, ix and plain getitem are position-based.
                tm.assert_series_equal(s[l_slc], s.iloc[i_slc])
                tm.assert_series_equal(s.loc[l_slc], s.iloc[i_slc])

        for idx in [_mklbl('A', 20), np.arange(20) + 100,
                    np.linspace(100, 150, 20)]:
            idx = Index(idx)
            s = Series(np.arange(20), index=idx)
            assert_slices_equivalent(SLC[idx[9]::-1], SLC[9::-1])
            assert_slices_equivalent(SLC[:idx[9]:-1], SLC[:8:-1])
            assert_slices_equivalent(SLC[idx[13]:idx[9]:-1], SLC[13:8:-1])
            assert_slices_equivalent(SLC[idx[9]:idx[13]:-1], SLC[:0]) 
Example #29
Source File: test_style.py    From recruit with Apache License 2.0 6 votes vote down vote up
def test_where_subset(self):
        # GH 17474
        def f(x):
            return x > 0.5

        style1 = 'foo: bar'
        style2 = 'baz: foo'

        slices = [pd.IndexSlice[:], pd.IndexSlice[:, ['A']],
                  pd.IndexSlice[[1], :], pd.IndexSlice[[1], ['A']],
                  pd.IndexSlice[:2, ['A', 'B']]]

        for slice_ in slices:
            result = self.df.style.where(f, style1, style2,
                                         subset=slice_)._compute().ctx
            expected = {(r, c):
                        [style1 if f(self.df.loc[row, col]) else style2]
                        for r, row in enumerate(self.df.index)
                        for c, col in enumerate(self.df.columns)
                        if row in self.df.loc[slice_].index and
                        col in self.df.loc[slice_].columns}
            assert result == expected 
Example #30
Source File: test_style.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def test_set_properties_subset(self):
        df = pd.DataFrame({'A': [0, 1]})
        result = df.style.set_properties(subset=pd.IndexSlice[0, 'A'],
                                         color='white')._compute().ctx
        expected = {(0, 0): ['color: white']}
        assert result == expected