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

时间:2017-12-02 19:32:34

标签: python-3.x pandas

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

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

1 个答案:

答案 0 :(得分:2)

经过几次挖掘(谷歌搜索)和脑力冲击问题后,我得到了答案。以下是更正的功能:

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的新手,如果我的理解是错误的,请纠正我!

修改

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