2017-12-02 85 views
1

我寫了下面的功能。當調用它時,它將拋出KeyError爲dataset.loc[]調用。我想了解爲什麼會發生這種情況,以及如何避免這種情況發生。熊貓 - KeyError異常:「不能用一個單一的布爾索引到setitem」

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

我只是看了一眼,並沒有100%確定你在做什麼,但有一個熊貓方法,'replace() 「這需要一本詞典,比如說」dct「作爲一個參數。所以你可能可以像'df.replace(dct)'那樣做上面的事情。例如。在這裏看到:https://stackoverflow.com/questions/20250771/remap-values-in-pandas-column-with-a-dict/41678874#41678874 – JohnE

+0

感謝您的建議@JohnE!我仔細閱讀了文檔,並想出瞭如何使用replace()來滿足我的需求。 –

+0

當然,沒問題! – JohnE

回答

1

我得到了答案後,很少挖掘(谷歌搜索)和頭腦風暴的問題。以下是校正功能:

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 

注意,我已刪除從中引起鍵dataset.loc作爲標布爾值,而不是一系列的值,這裏需要以指向比較str()目標系列中每個值的結果條件。所以通過刪除str()它導致了一個布爾序列,這是我們整個工作所需要的。

我是新來的蟒蛇,如果我的理解是錯在這裏,請大家指正!

編輯:

至於建議的@JohnE,我試圖實現,也可以使用熊貓replace()方法很容易做到的功能。我正在推出相應的實施,因爲它可以幫助某人:

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