首页 > 解决方案 > np.where() 和条件运算符的问题 - “ValueError:对于参数“就地”预期类型 bool,接收类型 Series。”

问题描述

我最喜欢的 np 函数在一夜之间发生了一些事情,我不明白是什么?下面的代码曾经工作得很好,现在我收到以下错误

data = {'text':  ['Facotry One fired', 'Second value', 'Match'],
        'H&S': [1, 0 , 0]}
df_test = pd.DataFrame(data, columns = ['text','H&S'])
df_test['H&S'] = np.where(df_test['text'].str.contains('fired'), 0, df_test['H&S']) 

预期结果

data = {'text':  ['Facotry One fired', 'Second value', 'Match'],
            'H&S': [0, 0 , 0]}
    df_test = pd.DataFrame(data, columns = ['text','H&S'])

错误:

ValueError                                Traceback (most recent call last)
<ipython-input-28-d8607dc64cae> in <module>
      4 df_test = pd.DataFrame(data, columns = ['text','H&S'])
      5 
----> 6 df_test['H&S'] = np.where(df_test['text'].str.contains('fired'), 0, df_test['H&S'])

~\anaconda3\lib\site-packages\pandas\core\generic.py in where(self, cond, other, inplace, axis, level, errors, try_cast)
   8916 
   8917         other = com.apply_if_callable(other, self)
-> 8918         return self._where(
   8919             cond, other, inplace, axis, level, errors=errors, try_cast=try_cast
   8920         )

~\anaconda3\lib\site-packages\pandas\core\generic.py in _where(self, cond, other, inplace, axis, level, errors, try_cast)
   8649         applied as a function even if callable. Used in __setitem__.
   8650         """
-> 8651         inplace = validate_bool_kwarg(inplace, "inplace")
   8652 
   8653         # align the cond to same shape as myself

~\anaconda3\lib\site-packages\pandas\util\_validators.py in validate_bool_kwarg(value, arg_name)
    208     """ Ensures that argument passed in arg_name is of type bool. """
    209     if not (is_bool(value) or value is None):
--> 210         raise ValueError(
    211             f'For argument "{arg_name}" expected type bool, received '
    212             f"type {type(value).__name__}."

ValueError: For argument "inplace" expected type bool, received type Series.

标签: pythonpandasnumpy

解决方案


查看 StackTrace 的第 7 行。它包含:

lib\site-packages\pandas\core\generic.py

所以你在这里调用 where 的pandasonic版本(不是 Numpythonic)。

然后查看pandas.DataFrame.where的文档,特别是参数的顺序。请注意,第三个参数是就地的,它应该是bool类型。

另请注意,指令中的第三个参数是 DataFrame 列(实际上只是一个Series)。

所以可能在你执行违规指令时 np包含一个DataFrame(而不是Numpy模块)。

要检查这一点,请print(type(np))在违规指令之前添加。在正常情况下,您应该得到module。但是,如果我是对的(在您的代码中较早的地方执行了类似的操作 np = <some DataFrame>),您将得到pandas.core.frame.DataFrame

如果我是对的,请检查您的代码,找到Numpy模块在哪里被 DataFrame 覆盖,然后在这个地方用任何其他名称更改np 。


推荐阅读