python-3.x - Pandas - KeyError : 'cannot use a single bool to index into setitem'

标签 python-3.x pandas

我编写了以下函数。调用它时,它抛出 KeyError for 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
    }
})

错误:
---------------------------------------------------------------------------
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 函数实现的目标

最佳答案

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

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 的关键的比较作为标量 bool 值而不是系列值,这里需要它以指向目标系列中每个值的结果条件。因此,通过删除 str()结果是一个 bool 系列,这是我们整个工作所需要的。

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

编辑:

正如 @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
        }
    })

关于python-3.x - Pandas - KeyError : 'cannot use a single bool to index into setitem' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47611728/

相关文章:

python-3.x - 唯一索引抛出 : Reindexing only valid with uniquely valued Index objects

python - 如何将键映射到多个值到数据框列?

python-3.x - 如何在 python 中的 DXF 中查找形状的尺寸?

python - Pandas 系统地识别缺失的多索引分类值

Python Pandas : Split DateTimeIndex in two at missing timestamp

python - 处理选定行时避免 pandas 数据框中的 for 循环

Python:如何拆分数据框中的字符串列?

Python最准确测量时间(毫秒)的方法

python - 用Python读取Large Json并取一个切片作为样本

python - 将 Pandas 数据框传递给 Django 模板