首页 > 解决方案 > pandas.Series 中的字符串总是小于 0 吗?

问题描述

当我评估以下代码片段时,我得到了值True

import pandas as pd
df = pd.DataFrame({'a': ['assa', '100', 'AJSAND']})
(df < 0).all()

在 Pandas DataFrame 中字符串的计算结果是否总是小于零?

但是,以下导致错误

's' < 0

标签: pythonpandas

解决方案


如果您查看 pandas 的源代码,您可以在_comp_method_FRAME方法下找到以下几行。你可以在这里找到完整的解释。总而言之,它更多的是一种比较每种类型而不会导致异常的方法。

def _comp_method_FRAME(cls, func, special):
    str_rep = _get_opstr(func, cls)
    op_name = _get_op_name(func, special)

    @Appender('Wrapper for comparison method {name}'.format(name=op_name))
    def f(self, other):
        if isinstance(other, ABCDataFrame):
            # Another DataFrame
            if not self._indexed_same(other):
                raise ValueError('Can only compare identically-labeled '
                                 'DataFrame objects')
            return self._compare_frame(other, func, str_rep)

        elif isinstance(other, ABCSeries):
            return _combine_series_frame(self, other, func,
                                         fill_value=None, axis=None,
                                         level=None, try_cast=False)
        else:

            # straight boolean comparisons we want to allow all columns
            # (regardless of dtype to pass thru) See #4537 for discussion.
            res = self._combine_const(other, func,
                                      errors='ignore',
                                      try_cast=False)
            return res.fillna(True).astype(bool)

    f.__name__ = op_name

    return f

所以基本上数据框首先用 NaN 填充,然后用真正的布尔值删除!


推荐阅读