Pandas - KeyError:“无法使用单个布尔值来索引 setitem”

2024-04-29

我写了以下函数。调用它时,它会抛出 KeyErrordataset.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'

另外,请告诉我是否有更好/正确的方法来实现我尝试使用 ChangeColumnValues 函数实现的目标


经过一番挖掘(谷歌搜索)和头脑风暴后我得到了答案。以下是更正后的函数:

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

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

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

Edit:

正如建议的@JohnE https://stackoverflow.com/users/3877338/johne,我想要实现的功能也可以使用 pandas 轻松完成replace()方法。我正在实施相应的实施,因为它可以对某人有所帮助:

BankDS = BankDS.replace({
        'Default': {
            'no': -1,
            'yes': 1
        },
        'Housing': {
            'no': -1,
            'yes': 1
        },
        'Loan': {
            'no': -1,
            'yes': 1
        },
        'Y': {
            'no': 0,
            'yes': 1
        }
    })
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Pandas - KeyError:“无法使用单个布尔值来索引 setitem” 的相关文章

随机推荐