Python pandas.core.dtypes.common.is_list_like() Examples

The following are 30 code examples of pandas.core.dtypes.common.is_list_like(). 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.dtypes.common , or try the search function .
Example #1
Source File: pivot.py    From recruit with Apache License 2.0 6 votes vote down vote up
def pivot(data, index=None, columns=None, values=None):
    if values is None:
        cols = [columns] if index is None else [index, columns]
        append = index is None
        indexed = data.set_index(cols, append=append)
    else:
        if index is None:
            index = data.index
        else:
            index = data[index]
        index = MultiIndex.from_arrays([index, data[columns]])

        if is_list_like(values) and not isinstance(values, tuple):
            # Exclude tuple because it is seen as a single column name
            indexed = data._constructor(data[values].values, index=index,
                                        columns=values)
        else:
            indexed = data._constructor_sliced(data[values].values,
                                               index=index)
    return indexed.unstack(columns) 
Example #2
Source File: pivot.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def pivot(data, index=None, columns=None, values=None):
    if values is None:
        cols = [columns] if index is None else [index, columns]
        append = index is None
        indexed = data.set_index(cols, append=append)
    else:
        if index is None:
            index = data.index
        else:
            index = data[index]
        index = MultiIndex.from_arrays([index, data[columns]])

        if is_list_like(values) and not isinstance(values, tuple):
            # Exclude tuple because it is seen as a single column name
            indexed = data._constructor(data[values].values, index=index,
                                        columns=values)
        else:
            indexed = data._constructor_sliced(data[values].values,
                                               index=index)
    return indexed.unstack(columns) 
Example #3
Source File: pytables.py    From Splunking-Crime with GNU Affero General Public License v3.0 6 votes vote down vote up
def _validate_where(w):
    """
    Validate that the where statement is of the right type.

    The type may either be String, Expr, or list-like of Exprs.

    Parameters
    ----------
    w : String term expression, Expr, or list-like of Exprs.

    Returns
    -------
    where : The original where clause if the check was successful.

    Raises
    ------
    TypeError : An invalid data type was passed in for w (e.g. dict).
    """

    if not (isinstance(w, (Expr, string_types)) or is_list_like(w)):
        raise TypeError("where must be passed as a string, Expr, "
                        "or list-like of Exprs")

    return w 
Example #4
Source File: pytables.py    From elasticintel with GNU General Public License v3.0 6 votes vote down vote up
def _validate_where(w):
    """
    Validate that the where statement is of the right type.

    The type may either be String, Expr, or list-like of Exprs.

    Parameters
    ----------
    w : String term expression, Expr, or list-like of Exprs.

    Returns
    -------
    where : The original where clause if the check was successful.

    Raises
    ------
    TypeError : An invalid data type was passed in for w (e.g. dict).
    """

    if not (isinstance(w, (Expr, string_types)) or is_list_like(w)):
        raise TypeError("where must be passed as a string, Expr, "
                        "or list-like of Exprs")

    return w 
Example #5
Source File: pytables.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def _validate_where(w):
    """
    Validate that the where statement is of the right type.

    The type may either be String, Expr, or list-like of Exprs.

    Parameters
    ----------
    w : String term expression, Expr, or list-like of Exprs.

    Returns
    -------
    where : The original where clause if the check was successful.

    Raises
    ------
    TypeError : An invalid data type was passed in for w (e.g. dict).
    """

    if not (isinstance(w, (Expr, string_types)) or is_list_like(w)):
        raise TypeError("where must be passed as a string, Expr, "
                        "or list-like of Exprs")

    return w 
Example #6
Source File: pytables.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def conform(self, rhs):
        """ inplace conform rhs """
        if not is_list_like(rhs):
            rhs = [rhs]
        if isinstance(rhs, np.ndarray):
            rhs = rhs.ravel()
        return rhs 
Example #7
Source File: _tools.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _flatten(axes):
    if not is_list_like(axes):
        return np.array([axes])
    elif isinstance(axes, (np.ndarray, ABCIndexClass)):
        return axes.ravel()
    return np.array(axes) 
Example #8
Source File: html.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def _get_skiprows(skiprows):
    """Get an iterator given an integer, slice or container.

    Parameters
    ----------
    skiprows : int, slice, container
        The iterator to use to skip rows; can also be a slice.

    Raises
    ------
    TypeError
        * If `skiprows` is not a slice, integer, or Container

    Returns
    -------
    it : iterable
        A proper iterator to use to skip rows of a DataFrame.
    """
    if isinstance(skiprows, slice):
        return lrange(skiprows.start or 0, skiprows.stop, skiprows.step or 1)
    elif isinstance(skiprows, numbers.Integral) or is_list_like(skiprows):
        return skiprows
    elif skiprows is None:
        return 0
    raise TypeError('%r is not a valid type for skipping rows' %
                    type(skiprows).__name__) 
Example #9
Source File: _tools.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def _flatten(axes):
    if not is_list_like(axes):
        return np.array([axes])
    elif isinstance(axes, (np.ndarray, Index)):
        return axes.ravel()
    return np.array(axes) 
Example #10
Source File: pytables.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def conform(self, rhs):
        """ inplace conform rhs """
        if not is_list_like(rhs):
            rhs = [rhs]
        if isinstance(rhs, np.ndarray):
            rhs = rhs.ravel()
        return rhs 
Example #11
Source File: ops.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def _in(x, y):
    """Compute the vectorized membership of ``x in y`` if possible, otherwise
    use Python.
    """
    try:
        return x.isin(y)
    except AttributeError:
        if is_list_like(x):
            try:
                return y.isin(x)
            except AttributeError:
                pass
        return x in y 
Example #12
Source File: html.py    From Splunking-Crime with GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_skiprows(skiprows):
    """Get an iterator given an integer, slice or container.

    Parameters
    ----------
    skiprows : int, slice, container
        The iterator to use to skip rows; can also be a slice.

    Raises
    ------
    TypeError
        * If `skiprows` is not a slice, integer, or Container

    Returns
    -------
    it : iterable
        A proper iterator to use to skip rows of a DataFrame.
    """
    if isinstance(skiprows, slice):
        return lrange(skiprows.start or 0, skiprows.stop, skiprows.step or 1)
    elif isinstance(skiprows, numbers.Integral) or is_list_like(skiprows):
        return skiprows
    elif skiprows is None:
        return 0
    raise TypeError('%r is not a valid type for skipping rows' %
                    type(skiprows).__name__) 
Example #13
Source File: _tools.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def _flatten(axes):
    if not is_list_like(axes):
        return np.array([axes])
    elif isinstance(axes, (np.ndarray, Index)):
        return axes.ravel()
    return np.array(axes) 
Example #14
Source File: test_eval.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def check_simple_cmp_op(self, lhs, cmp1, rhs):
        ex = 'lhs {0} rhs'.format(cmp1)
        if cmp1 in ('in', 'not in') and not is_list_like(rhs):
            pytest.raises(TypeError, pd.eval, ex, engine=self.engine,
                          parser=self.parser, local_dict={'lhs': lhs,
                                                          'rhs': rhs})
        else:
            expected = _eval_single_bin(lhs, cmp1, rhs, self.engine)
            result = pd.eval(ex, engine=self.engine, parser=self.parser)
            self.check_equal(result, expected) 
Example #15
Source File: base.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def _gotitem(self, key, ndim, subset=None):
        """
        Sub-classes to define. Return a sliced object.

        Parameters
        ----------
        key : string / list of selections
        ndim : 1,2
            requested ndim of result
        subset : object, default None
            subset to act on
        """
        # create a new object to prevent aliasing
        if subset is None:
            subset = self.obj

        # we need to make a shallow copy of ourselves
        # with the same groupby
        kwargs = {attr: getattr(self, attr) for attr in self._attributes}

        # Try to select from a DataFrame, falling back to a Series
        try:
            groupby = self._groupby[key]
        except IndexError:
            groupby = self._groupby

        self = self.__class__(subset,
                              groupby=groupby,
                              parent=self,
                              **kwargs)
        self._reset_cache()
        if subset.ndim == 2:
            if is_scalar(key) and key in subset or is_list_like(key):
                self._selection = key
        return self


# special case to prevent duplicate plots when catching exceptions when
# forwarding methods from NDFrames 
Example #16
Source File: ops.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def _not_in(x, y):
    """Compute the vectorized membership of ``x not in y`` if possible,
    otherwise use Python.
    """
    try:
        return ~x.isin(y)
    except AttributeError:
        if is_list_like(x):
            try:
                return ~y.isin(x)
            except AttributeError:
                pass
        return x not in y 
Example #17
Source File: html.py    From elasticintel with GNU General Public License v3.0 5 votes vote down vote up
def _get_skiprows(skiprows):
    """Get an iterator given an integer, slice or container.

    Parameters
    ----------
    skiprows : int, slice, container
        The iterator to use to skip rows; can also be a slice.

    Raises
    ------
    TypeError
        * If `skiprows` is not a slice, integer, or Container

    Returns
    -------
    it : iterable
        A proper iterator to use to skip rows of a DataFrame.
    """
    if isinstance(skiprows, slice):
        return lrange(skiprows.start or 0, skiprows.stop, skiprows.step or 1)
    elif isinstance(skiprows, numbers.Integral) or is_list_like(skiprows):
        return skiprows
    elif skiprows is None:
        return 0
    raise TypeError('%r is not a valid type for skipping rows' %
                    type(skiprows).__name__) 
Example #18
Source File: groupby.py    From modin with Apache License 2.0 5 votes vote down vote up
def aggregate(self, func=None, *args, **kwargs):
        if self._axis != 0:
            # This is not implemented in pandas,
            # so we throw a different message
            raise NotImplementedError("axis other than 0 is not supported")

        if func is None or is_list_like(func):
            return self._default_to_pandas(
                lambda df: df.aggregate(func, *args, **kwargs)
            )
        return self._apply_agg_function(
            lambda df: df.aggregate(func, *args, **kwargs), drop=self._as_index
        ) 
Example #19
Source File: groupby.py    From modin with Apache License 2.0 5 votes vote down vote up
def quantile(self, q=0.5, **kwargs):
        import numpy as np

        if self.ndim > 1:
            if self._df.dtypes.map(lambda x: x == np.dtype("O")).any():
                raise TypeError(
                    "'quantile' cannot be performed against 'object' dtypes!"
                )
        elif self._df.dtypes == np.dtype("O"):
            raise TypeError("'quantile' cannot be performed against 'object' dtypes!")
        if is_list_like(q):
            return self._default_to_pandas(lambda df: df.quantile(q=q, **kwargs))

        return self._apply_agg_function(lambda df: df.quantile(q, **kwargs)) 
Example #20
Source File: utils.py    From AIF360 with Apache License 2.0 5 votes vote down vote up
def check_already_dropped(labels, dropped_cols, name, dropped_by='numeric_only',
                          warn=True):
    """Check if columns have already been dropped and return only those that
    haven't.

    Args:
        labels (single label or list-like): Column labels to check.
        dropped_cols (set or pandas.Index): Columns that were already dropped.
        name (str): Original arg that triggered the check (e.g. dropcols).
        dropped_by (str, optional): Original arg that caused dropped_cols``
            (e.g. numeric_only).
        warn (bool, optional): If ``True``, produces a
            :class:`ColumnAlreadyDroppedWarning` if there are columns in the
            intersection of dropped_cols and labels.

    Returns:
        list: Columns in labels which are not in dropped_cols.
    """
    if not is_list_like(labels):
        labels = [labels]
    str_labels = [c for c in labels if isinstance(c, str)]
    already_dropped = dropped_cols.intersection(str_labels)
    if warn and any(already_dropped):
        warnings.warn("Some column labels from `{}` were already dropped by "
                "`{}`:\n{}".format(name, dropped_by, already_dropped.tolist()),
                ColumnAlreadyDroppedWarning, stacklevel=2)
    return [c for c in labels if not isinstance(c, str) or c not in already_dropped] 
Example #21
Source File: _tools.py    From coffeegrindsize with MIT License 5 votes vote down vote up
def _flatten(axes):
    if not is_list_like(axes):
        return np.array([axes])
    elif isinstance(axes, (np.ndarray, ABCIndexClass)):
        return axes.ravel()
    return np.array(axes) 
Example #22
Source File: _tools.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def _flatten(axes):
    if not is_list_like(axes):
        return np.array([axes])
    elif isinstance(axes, (np.ndarray, Index)):
        return axes.ravel()
    return np.array(axes) 
Example #23
Source File: test_eval.py    From twitter-stock-recommendation with MIT License 5 votes vote down vote up
def check_simple_cmp_op(self, lhs, cmp1, rhs):
        ex = 'lhs {0} rhs'.format(cmp1)
        if cmp1 in ('in', 'not in') and not is_list_like(rhs):
            pytest.raises(TypeError, pd.eval, ex, engine=self.engine,
                          parser=self.parser, local_dict={'lhs': lhs,
                                                          'rhs': rhs})
        else:
            expected = _eval_single_bin(lhs, cmp1, rhs, self.engine)
            result = pd.eval(ex, engine=self.engine, parser=self.parser)
            self.check_equal(result, expected) 
Example #24
Source File: ops.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def _in(x, y):
    """Compute the vectorized membership of ``x in y`` if possible, otherwise
    use Python.
    """
    try:
        return x.isin(y)
    except AttributeError:
        if is_list_like(x):
            try:
                return y.isin(x)
            except AttributeError:
                pass
        return x in y 
Example #25
Source File: test_eval.py    From recruit with Apache License 2.0 5 votes vote down vote up
def check_simple_cmp_op(self, lhs, cmp1, rhs):
        ex = 'lhs {0} rhs'.format(cmp1)
        if cmp1 in ('in', 'not in') and not is_list_like(rhs):
            pytest.raises(TypeError, pd.eval, ex, engine=self.engine,
                          parser=self.parser, local_dict={'lhs': lhs,
                                                          'rhs': rhs})
        else:
            expected = _eval_single_bin(lhs, cmp1, rhs, self.engine)
            result = pd.eval(ex, engine=self.engine, parser=self.parser)
            self.check_equal(result, expected) 
Example #26
Source File: pytables.py    From recruit with Apache License 2.0 5 votes vote down vote up
def conform(self, rhs):
        """ inplace conform rhs """
        if not is_list_like(rhs):
            rhs = [rhs]
        if isinstance(rhs, np.ndarray):
            rhs = rhs.ravel()
        return rhs 
Example #27
Source File: ops.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _in(x, y):
    """Compute the vectorized membership of ``x in y`` if possible, otherwise
    use Python.
    """
    try:
        return x.isin(y)
    except AttributeError:
        if is_list_like(x):
            try:
                return y.isin(x)
            except AttributeError:
                pass
        return x in y 
Example #28
Source File: ops.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _not_in(x, y):
    """Compute the vectorized membership of ``x not in y`` if possible,
    otherwise use Python.
    """
    try:
        return ~x.isin(y)
    except AttributeError:
        if is_list_like(x):
            try:
                return ~y.isin(x)
            except AttributeError:
                pass
        return x not in y 
Example #29
Source File: base.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _gotitem(self, key, ndim, subset=None):
        """
        Sub-classes to define. Return a sliced object.

        Parameters
        ----------
        key : string / list of selections
        ndim : 1,2
            requested ndim of result
        subset : object, default None
            subset to act on
        """
        # create a new object to prevent aliasing
        if subset is None:
            subset = self.obj

        # we need to make a shallow copy of ourselves
        # with the same groupby
        kwargs = {attr: getattr(self, attr) for attr in self._attributes}

        # Try to select from a DataFrame, falling back to a Series
        try:
            groupby = self._groupby[key]
        except IndexError:
            groupby = self._groupby

        self = self.__class__(subset,
                              groupby=groupby,
                              parent=self,
                              **kwargs)
        self._reset_cache()
        if subset.ndim == 2:
            if is_scalar(key) and key in subset or is_list_like(key):
                self._selection = key
        return self


# special case to prevent duplicate plots when catching exceptions when
# forwarding methods from NDFrames 
Example #30
Source File: html.py    From recruit with Apache License 2.0 5 votes vote down vote up
def _get_skiprows(skiprows):
    """Get an iterator given an integer, slice or container.

    Parameters
    ----------
    skiprows : int, slice, container
        The iterator to use to skip rows; can also be a slice.

    Raises
    ------
    TypeError
        * If `skiprows` is not a slice, integer, or Container

    Returns
    -------
    it : iterable
        A proper iterator to use to skip rows of a DataFrame.
    """
    if isinstance(skiprows, slice):
        return lrange(skiprows.start or 0, skiprows.stop, skiprows.step or 1)
    elif isinstance(skiprows, numbers.Integral) or is_list_like(skiprows):
        return skiprows
    elif skiprows is None:
        return 0
    raise TypeError('%r is not a valid type for skipping rows' %
                    type(skiprows).__name__)