Pandas - KeyError: '不能使用单个 bool 索引到 setitem'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47611728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:51:32  来源:igfitidea点击:

Pandas - KeyError: 'cannot use a single bool to index into setitem'

python-3.xpandas

提问by Benison Sam

I have written the following function. When calling it, it throws KeyError for dataset.loc[]call. I would like to understand why this is happening and how to avoid the same.

我编写了以下函数。调用它时,它会抛出 KeyError 以进行dataset.loc[]调用。我想了解为什么会发生这种情况以及如何避免这种情况。

def ChangeColumnValues(dataset, columnValues):
    """Changes the values of given columns into the given key value pairs

    :: Argument Description ::
    dataset - Dataset for which the values are to be updated
    columnValues - Dictionary with Column and Value-Replacement pair
    """

    for column, valuePair in columnValues.items():
        for value, replacement in valuePair.items():
            dataset.loc[str(dataset[column]) == value, column] = replacement

    return dataset

BankDS = da.ChangeColumnValues(BankDS, {
    'Default': {
        'no': -1,
        'yes': 1
    },
    'Housing': {
        'no': -1,
        'yes': 1
    },
    'Loan': {
        'no': -1,
        'yes': 1
    },
    'Y': {
        'no': 0,
        'yes': 1
    }
})

Error:

错误:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-20-0c766179be88> in <module>()
     30     WineQualityDS = da.MeanNormalize(WineQualityDS)
     31 
---> 32 PreProcessDataSets()

<ipython-input-20-0c766179be88> in PreProcessDataSets()
     20         'Y': {
     21             'no': 0,
---> 22             'yes': 1
     23         }
     24     })

W:\MyProjects\Python\ML\FirstOne\DAHelper\DataSet.py in ChangeColumnValues(dataset, columnValues)
     73     for column, valuePair in columnValues.items():
     74         for value, replacement in valuePair.items():
---> 75             dataset.loc[str(dataset[column]) == value, column] = replacement
     76 
     77     return dataset

C:\Program Files\Anaconda3\lib\site-packages\pandas\core\indexing.py in __setitem__(self, key, value)
    177             key = com._apply_if_callable(key, self.obj)
    178         indexer = self._get_setitem_indexer(key)
--> 179         self._setitem_with_indexer(indexer, value)
    180 
    181     def _has_valid_type(self, k, axis):

C:\Program Files\Anaconda3\lib\site-packages\pandas\core\indexing.py in _setitem_with_indexer(self, indexer, value)
    310                     # reindex the axis to the new value
    311                     # and set inplace
--> 312                     key, _ = convert_missing_indexer(idx)
    313 
    314                     # if this is the items axes, then take the main missing

C:\Program Files\Anaconda3\lib\site-packages\pandas\core\indexing.py in convert_missing_indexer(indexer)
   1963 
   1964         if isinstance(indexer, bool):
-> 1965             raise KeyError("cannot use a single bool to index into setitem")
   1966         return indexer, True
   1967 

KeyError: 'cannot use a single bool to index into setitem'

Also please let me know if there any better/right way to implement what I am trying achieve with ChangeColumnValues function

另外请让我知道是否有更好/正确的方法来实现我正在尝试使用 ChangeColumnValues 函数实现的目标

回答by Benison Sam

I got the answer after a few digging (google searches) and brain storming into the issue. Following is the corrected function:

经过几次挖掘(谷歌搜索)和头脑风暴后,我得到了这个问题的答案。以下是修正后的函数:

def ChangeColumnValues(dataset, columnValues):
    """Changes the values of given columns into the given key value pairs

    :: Argument Description ::
    dataset - Dataset for which the values are to be updated
    columnValues - Dictionary with Column and Value-Replacement pair
    """

    for column, valuePair in columnValues.items():
        for value, replacement in valuePair.items():
            dataset.loc[dataset[column] == value, column] = replacement

    return dataset

Note that I have removed the str()from the comparison which was causing the key for dataset.locas a scalar boolean value rather than a series value, which is needed here in order to point to the resultant condition for each value in the target series. So by removing the str()it resulted to be a boolean series which is what we need for the whole thing to work.

请注意,我已从str()比较中删除了导致键为dataset.loc标量布尔值而不是系列值的比较,这里需要它以指向目标系列中每个值的结果条件。因此,通过删除str()它会导致一个布尔系列,这是我们整个工作所需的。

I am new to python, if my understanding is wrong here, please correct me!

我是python新手,如果我的理解有误,请指正!

Edit:

编辑:

As suggested by @JohnE, the functionality which I was trying to achieve can also be done easily using pandas replace()method. I am putting in a corresponding implementation as it can be of help to someone:

正如@JohnE所建议的,我试图实现的功能也可以使用 pandasreplace()方法轻松完成。我正在放入相应的实现,因为它可以对某人有所帮助:

BankDS = BankDS.replace({
        'Default': {
            'no': -1,
            'yes': 1
        },
        'Housing': {
            'no': -1,
            'yes': 1
        },
        'Loan': {
            'no': -1,
            'yes': 1
        },
        'Y': {
            'no': 0,
            'yes': 1
        }
    })