Python pandas.core.indexing._non_reducing_slice() Examples

The following are 24 code examples of pandas.core.indexing._non_reducing_slice(). 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.core.indexing , or try the search function .
Example #1
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 #2
Source File: test_indexing.py    From elasticintel with GNU General Public License v3.0 6 votes vote down vote up
def test_non_reducing_slice(self):
        df = pd.DataFrame([[0, 1], [2, 3]])

        slices = [
            # pd.IndexSlice[:, :],
            pd.IndexSlice[:, 1],
            pd.IndexSlice[1, :],
            pd.IndexSlice[[1], [1]],
            pd.IndexSlice[1, [1]],
            pd.IndexSlice[[1], 1],
            pd.IndexSlice[1],
            pd.IndexSlice[1, 1],
            slice(None, None, None),
            [0, 1],
            np.array([0, 1]),
            pd.Series([0, 1])
        ]
        for slice_ in slices:
            tslice_ = _non_reducing_slice(slice_)
            assert isinstance(df.loc[tslice_], DataFrame) 
Example #3
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 #4
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 #5
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 #6
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 #7
Source File: style.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def _applymap(self, func, subset=None, **kwargs):
        func = partial(func, **kwargs)  # applymap doesn't take kwargs?
        if subset is None:
            subset = pd.IndexSlice[:]
        subset = _non_reducing_slice(subset)
        result = self.data.loc[subset].applymap(func)
        self._update_ctx(result)
        return self 
Example #8
Source File: style.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def background_gradient(self, cmap='PuBu', low=0, high=0, axis=0,
                            subset=None):
        """
        Color the background in a gradient according to
        the data in each column (optionally row).
        Requires matplotlib.

        .. versionadded:: 0.17.1

        Parameters
        ----------
        cmap: str or colormap
            matplotlib colormap
        low, high: float
            compress the range by these values.
        axis: int or str
            1 or 'columns' for columnwise, 0 or 'index' for rowwise
        subset: IndexSlice
            a valid slice for ``data`` to limit the style application to

        Returns
        -------
        self : Styler

        Notes
        -----
        Tune ``low`` and ``high`` to keep the text legible by
        not using the entire range of the color map. These extend
        the range of the data by ``low * (x.max() - x.min())``
        and ``high * (x.max() - x.min())`` before normalizing.
        """
        subset = _maybe_numeric_slice(self.data, subset)
        subset = _non_reducing_slice(subset)
        self.apply(self._background_gradient, cmap=cmap, subset=subset,
                   axis=axis, low=low, high=high)
        return self 
Example #9
Source File: style.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def _applymap(self, func, subset=None, **kwargs):
        func = partial(func, **kwargs)  # applymap doesn't take kwargs?
        if subset is None:
            subset = pd.IndexSlice[:]
        subset = _non_reducing_slice(subset)
        result = self.data.loc[subset].applymap(func)
        self._update_ctx(result)
        return self 
Example #10
Source File: style.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def _apply(self, func, axis=0, subset=None, **kwargs):
        subset = slice(None) if subset is None else subset
        subset = _non_reducing_slice(subset)
        data = self.data.loc[subset]
        if axis is not None:
            result = data.apply(func, axis=axis, **kwargs)
        else:
            result = func(data, **kwargs)
            if not isinstance(result, pd.DataFrame):
                raise TypeError(
                    "Function {func!r} must return a DataFrame when "
                    "passed to `Styler.apply` with axis=None"
                    .format(func=func))
            if not (result.index.equals(data.index) and
                    result.columns.equals(data.columns)):
                msg = ('Result of {func!r} must have identical index and '
                       'columns as the input'.format(func=func))
                raise ValueError(msg)

        result_shape = result.shape
        expected_shape = self.data.loc[subset].shape
        if result_shape != expected_shape:
            msg = ("Function {func!r} returned the wrong shape.\n"
                   "Result has shape: {res}\n"
                   "Expected shape:   {expect}".format(func=func,
                                                       res=result.shape,
                                                       expect=expected_shape))
            raise ValueError(msg)
        self._update_ctx(result)
        return self 
Example #11
Source File: test_indexing.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def test_list_slice(self):
        # like dataframe getitem
        slices = [['A'], pd.Series(['A']), np.array(['A'])]
        df = pd.DataFrame({'A': [1, 2], 'B': [3, 4]}, index=['A', 'B'])
        expected = pd.IndexSlice[:, ['A']]
        for subset in slices:
            result = _non_reducing_slice(subset)
            tm.assert_frame_equal(df.loc[result], df.loc[expected]) 
Example #12
Source File: style.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def _highlight_handler(self, subset=None, color='yellow', axis=None,
                           max_=True):
        subset = _non_reducing_slice(_maybe_numeric_slice(self.data, subset))
        self.apply(self._highlight_extrema, color=color, axis=axis,
                   subset=subset, max_=max_)
        return self 
Example #13
Source File: style.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def background_gradient(self, cmap='PuBu', low=0, high=0, axis=0,
                            subset=None):
        """
        Color the background in a gradient according to
        the data in each column (optionally row).
        Requires matplotlib.

        .. versionadded:: 0.17.1

        Parameters
        ----------
        cmap: str or colormap
            matplotlib colormap
        low, high: float
            compress the range by these values.
        axis: int or str
            1 or 'columns' for columnwise, 0 or 'index' for rowwise
        subset: IndexSlice
            a valid slice for ``data`` to limit the style application to

        Returns
        -------
        self : Styler

        Notes
        -----
        Tune ``low`` and ``high`` to keep the text legible by
        not using the entire range of the color map. These extend
        the range of the data by ``low * (x.max() - x.min())``
        and ``high * (x.max() - x.min())`` before normalizing.
        """
        subset = _maybe_numeric_slice(self.data, subset)
        subset = _non_reducing_slice(subset)
        self.apply(self._background_gradient, cmap=cmap, subset=subset,
                   axis=axis, low=low, high=high)
        return self 
Example #14
Source File: style.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def _applymap(self, func, subset=None, **kwargs):
        func = partial(func, **kwargs)  # applymap doesn't take kwargs?
        if subset is None:
            subset = pd.IndexSlice[:]
        subset = _non_reducing_slice(subset)
        result = self.data.loc[subset].applymap(func)
        self._update_ctx(result)
        return self 
Example #15
Source File: style.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def _apply(self, func, axis=0, subset=None, **kwargs):
        subset = slice(None) if subset is None else subset
        subset = _non_reducing_slice(subset)
        data = self.data.loc[subset]
        if axis is not None:
            result = data.apply(func, axis=axis, **kwargs)
        else:
            result = func(data, **kwargs)
            if not isinstance(result, pd.DataFrame):
                raise TypeError(
                    "Function {func!r} must return a DataFrame when "
                    "passed to `Styler.apply` with axis=None"
                    .format(func=func))
            if not (result.index.equals(data.index) and
                    result.columns.equals(data.columns)):
                msg = ('Result of {func!r} must have identical index and '
                       'columns as the input'.format(func=func))
                raise ValueError(msg)

        result_shape = result.shape
        expected_shape = self.data.loc[subset].shape
        if result_shape != expected_shape:
            msg = ("Function {func!r} returned the wrong shape.\n"
                   "Result has shape: {res}\n"
                   "Expected shape:   {expect}".format(func=func,
                                                       res=result.shape,
                                                       expect=expected_shape))
            raise ValueError(msg)
        self._update_ctx(result)
        return self 
Example #16
Source File: style.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def _apply(self, func, axis=0, subset=None, **kwargs):
        subset = slice(None) if subset is None else subset
        subset = _non_reducing_slice(subset)
        data = self.data.loc[subset]
        if axis is not None:
            result = data.apply(func, axis=axis,
                                result_type='expand', **kwargs)
            result.columns = data.columns
        else:
            result = func(data, **kwargs)
            if not isinstance(result, pd.DataFrame):
                raise TypeError(
                    "Function {func!r} must return a DataFrame when "
                    "passed to `Styler.apply` with axis=None"
                    .format(func=func))
            if not (result.index.equals(data.index) and
                    result.columns.equals(data.columns)):
                msg = ('Result of {func!r} must have identical index and '
                       'columns as the input'.format(func=func))
                raise ValueError(msg)

        result_shape = result.shape
        expected_shape = self.data.loc[subset].shape
        if result_shape != expected_shape:
            msg = ("Function {func!r} returned the wrong shape.\n"
                   "Result has shape: {res}\n"
                   "Expected shape:   {expect}".format(func=func,
                                                       res=result.shape,
                                                       expect=expected_shape))
            raise ValueError(msg)
        self._update_ctx(result)
        return self 
Example #17
Source File: style.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def background_gradient(self, cmap='PuBu', low=0, high=0, axis=0,
                            subset=None):
        """
        Color the background in a gradient according to
        the data in each column (optionally row).
        Requires matplotlib.

        Parameters
        ----------
        cmap: str or colormap
            matplotlib colormap
        low, high: float
            compress the range by these values.
        axis: int or str
            1 or 'columns' for columnwise, 0 or 'index' for rowwise
        subset: IndexSlice
            a valid slice for ``data`` to limit the style application to

        Returns
        -------
        self : Styler

        Notes
        -----
        Tune ``low`` and ``high`` to keep the text legible by
        not using the entire range of the color map. These extend
        the range of the data by ``low * (x.max() - x.min())``
        and ``high * (x.max() - x.min())`` before normalizing.
        """
        subset = _maybe_numeric_slice(self.data, subset)
        subset = _non_reducing_slice(subset)
        self.apply(self._background_gradient, cmap=cmap, subset=subset,
                   axis=axis, low=low, high=high)
        return self 
Example #18
Source File: style.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _applymap(self, func, subset=None, **kwargs):
        func = partial(func, **kwargs)  # applymap doesn't take kwargs?
        if subset is None:
            subset = pd.IndexSlice[:]
        subset = _non_reducing_slice(subset)
        result = self.data.loc[subset].applymap(func)
        self._update_ctx(result)
        return self 
Example #19
Source File: style.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _apply(self, func, axis=0, subset=None, **kwargs):
        subset = slice(None) if subset is None else subset
        subset = _non_reducing_slice(subset)
        data = self.data.loc[subset]
        if axis is not None:
            result = data.apply(func, axis=axis,
                                result_type='expand', **kwargs)
            result.columns = data.columns
        else:
            result = func(data, **kwargs)
            if not isinstance(result, pd.DataFrame):
                raise TypeError(
                    "Function {func!r} must return a DataFrame when "
                    "passed to `Styler.apply` with axis=None"
                    .format(func=func))
            if not (result.index.equals(data.index) and
                    result.columns.equals(data.columns)):
                msg = ('Result of {func!r} must have identical index and '
                       'columns as the input'.format(func=func))
                raise ValueError(msg)

        result_shape = result.shape
        expected_shape = self.data.loc[subset].shape
        if result_shape != expected_shape:
            msg = ("Function {func!r} returned the wrong shape.\n"
                   "Result has shape: {res}\n"
                   "Expected shape:   {expect}".format(func=func,
                                                       res=result.shape,
                                                       expect=expected_shape))
            raise ValueError(msg)
        self._update_ctx(result)
        return self 
Example #20
Source File: style.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _applymap(self, func, subset=None, **kwargs):
        func = partial(func, **kwargs)  # applymap doesn't take kwargs?
        if subset is None:
            subset = pd.IndexSlice[:]
        subset = _non_reducing_slice(subset)
        result = self.data.loc[subset].applymap(func)
        self._update_ctx(result)
        return self 
Example #21
Source File: style.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _apply(self, func, axis=0, subset=None, **kwargs):
        subset = slice(None) if subset is None else subset
        subset = _non_reducing_slice(subset)
        data = self.data.loc[subset]
        if axis is not None:
            result = data.apply(func, axis=axis,
                                result_type='expand', **kwargs)
            result.columns = data.columns
        else:
            result = func(data, **kwargs)
            if not isinstance(result, pd.DataFrame):
                raise TypeError(
                    "Function {func!r} must return a DataFrame when "
                    "passed to `Styler.apply` with axis=None"
                    .format(func=func))
            if not (result.index.equals(data.index) and
                    result.columns.equals(data.columns)):
                msg = ('Result of {func!r} must have identical index and '
                       'columns as the input'.format(func=func))
                raise ValueError(msg)

        result_shape = result.shape
        expected_shape = self.data.loc[subset].shape
        if result_shape != expected_shape:
            msg = ("Function {func!r} returned the wrong shape.\n"
                   "Result has shape: {res}\n"
                   "Expected shape:   {expect}".format(func=func,
                                                       res=result.shape,
                                                       expect=expected_shape))
            raise ValueError(msg)
        self._update_ctx(result)
        return self 
Example #22
Source File: style.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 4 votes vote down vote up
def background_gradient(self, cmap='PuBu', low=0, high=0, axis=0,
                            subset=None, text_color_threshold=0.408):
        """
        Color the background in a gradient according to
        the data in each column (optionally row).

        Requires matplotlib.

        Parameters
        ----------
        cmap : str or colormap
            matplotlib colormap
        low, high : float
            compress the range by these values.
        axis : int or str
            1 or 'columns' for columnwise, 0 or 'index' for rowwise
        subset : IndexSlice
            a valid slice for ``data`` to limit the style application to
        text_color_threshold : float or int
            luminance threshold for determining text color. Facilitates text
            visibility across varying background colors. From 0 to 1.
            0 = all text is dark colored, 1 = all text is light colored.

            .. versionadded:: 0.24.0

        Returns
        -------
        self : Styler

        Raises
        ------
        ValueError
            If ``text_color_threshold`` is not a value from 0 to 1.

        Notes
        -----
        Set ``text_color_threshold`` or tune ``low`` and ``high`` to keep the
        text legible by not using the entire range of the color map. The range
        of the data is extended by ``low * (x.max() - x.min())`` and ``high *
        (x.max() - x.min())`` before normalizing.
        """
        subset = _maybe_numeric_slice(self.data, subset)
        subset = _non_reducing_slice(subset)
        self.apply(self._background_gradient, cmap=cmap, subset=subset,
                   axis=axis, low=low, high=high,
                   text_color_threshold=text_color_threshold)
        return self 
Example #23
Source File: style.py    From vnpy_crypto with MIT License 4 votes vote down vote up
def bar(self, subset=None, axis=0, color='#d65f5f', width=100,
            align='left'):
        """
        Color the background ``color`` proptional to the values in each column.
        Excludes non-numeric data by default.

        Parameters
        ----------
        subset: IndexSlice, default None
            a valid slice for ``data`` to limit the style application to
        axis: int
        color: str or 2-tuple/list
            If a str is passed, the color is the same for both
            negative and positive numbers. If 2-tuple/list is used, the
            first element is the color_negative and the second is the
            color_positive (eg: ['#d65f5f', '#5fba7d'])
        width: float
            A number between 0 or 100. The largest value will cover ``width``
            percent of the cell's width
        align : {'left', 'zero',' mid'}, default 'left'
            - 'left' : the min value starts at the left of the cell
            - 'zero' : a value of zero is located at the center of the cell
            - 'mid' : the center of the cell is at (max-min)/2, or
              if values are all negative (positive) the zero is aligned
              at the right (left) of the cell

              .. versionadded:: 0.20.0

        Returns
        -------
        self : Styler
        """
        subset = _maybe_numeric_slice(self.data, subset)
        subset = _non_reducing_slice(subset)

        base = 'width: 10em; height: 80%;'

        if not(is_list_like(color)):
            color = [color, color]
        elif len(color) == 1:
            color = [color[0], color[0]]
        elif len(color) > 2:
            msg = ("Must pass `color` as string or a list-like"
                   " of length 2: [`color_negative`, `color_positive`]\n"
                   "(eg: color=['#d65f5f', '#5fba7d'])")
            raise ValueError(msg)

        if align == 'left':
            self.apply(self._bar_left, subset=subset, axis=axis, color=color,
                       width=width, base=base)
        elif align == 'zero':
            self.apply(self._bar_center_zero, subset=subset, axis=axis,
                       color=color, width=width, base=base)
        elif align == 'mid':
            self.apply(self._bar_center_mid, subset=subset, axis=axis,
                       color=color, width=width, base=base)
        else:
            msg = ("`align` must be one of {'left', 'zero',' mid'}")
            raise ValueError(msg)

        return self 
Example #24
Source File: style.py    From recruit with Apache License 2.0 4 votes vote down vote up
def background_gradient(self, cmap='PuBu', low=0, high=0, axis=0,
                            subset=None, text_color_threshold=0.408):
        """
        Color the background in a gradient according to
        the data in each column (optionally row).

        Requires matplotlib.

        Parameters
        ----------
        cmap : str or colormap
            matplotlib colormap
        low, high : float
            compress the range by these values.
        axis : int or str
            1 or 'columns' for columnwise, 0 or 'index' for rowwise
        subset : IndexSlice
            a valid slice for ``data`` to limit the style application to
        text_color_threshold : float or int
            luminance threshold for determining text color. Facilitates text
            visibility across varying background colors. From 0 to 1.
            0 = all text is dark colored, 1 = all text is light colored.

            .. versionadded:: 0.24.0

        Returns
        -------
        self : Styler

        Raises
        ------
        ValueError
            If ``text_color_threshold`` is not a value from 0 to 1.

        Notes
        -----
        Set ``text_color_threshold`` or tune ``low`` and ``high`` to keep the
        text legible by not using the entire range of the color map. The range
        of the data is extended by ``low * (x.max() - x.min())`` and ``high *
        (x.max() - x.min())`` before normalizing.
        """
        subset = _maybe_numeric_slice(self.data, subset)
        subset = _non_reducing_slice(subset)
        self.apply(self._background_gradient, cmap=cmap, subset=subset,
                   axis=axis, low=low, high=high,
                   text_color_threshold=text_color_threshold)
        return self