np.where()和条件运算符“ValueError”存在问题:对于参数“inplace”,预期类型为bool,接收类型为Series

2024-09-24 22:17:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我最喜欢的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.

Tags: textintestselfdfdatavaluetype
1条回答
网友
1楼 · 发布于 2024-09-24 22:17:47

看看StackTrace的第7行。它包括:

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

因此,您在这里调用的是pandasonic版本的,其中(不是 Numpythonic

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

还要注意,指令中的第三个参数是DataFrame列 (实际上,只是一个系列

所以很可能是在你执行这个有问题的指令的时候 np包含一个数据帧(而不是Numpy模块)

要检查这一点,请在有问题的指令之前添加print(type(np))。 在正常情况下,您应该获得模块。 但如果我是对的(在代码的前面,您执行了类似 np = <some DataFrame>),您将获得pandas.core.frame.DataFrame

如果我是对的,请检查您的代码,找到模块被覆盖的位置 使用数据帧并在此处使用任何其他名称更改np

相关问题 更多 >