2017-09-03 842 views
1

我的代碼是導致我的問題的段是類型錯誤:unhashable類型:「Int64Index」

def Half_Increase(self): 
    self.keg_count=summer17.iloc[self.result_rows,2].values[0] 
    self.keg_count +=1 
    summer17[self.result_rows,2] = self.keg_count 
    print(keg_count) 

所以這個功能是當按下按鈕控件執行。它應該從數據框中的特定單元格中獲取值,向其中添加1,然後將新值返回給數據框。 (我不能完全肯定,如果這是這樣做的正確方法。)

我收到以下錯誤

Exception in Tkinter callback 
Traceback (most recent call last): 

    File "C:\Python3.6\lib\tkinter\__init__.py", line 1699, in __call__ 
    return self.func(*args) 
    File "beerfest_program_v0.3.py", line 152, in Half_Increase 
    summer17[self.result_rows,2] = self.keg_count 
    File "C:\Python3.6\lib\site-packages\pandas\core\frame.py", line 2331, in __setitem__ 
    self._set_item(key, value) 
    File "C:\Python3.6\lib\site-packages\pandas\core\frame.py", line 2397, in _set_item 
    value = self._sanitize_column(key, value) 
    File "C:\Python3.6\lib\site-packages\pandas\core\frame.py", line 2596, in _sanitize_column 
    if broadcast and key in self.columns and value.ndim == 1: 
    File "C:\Python3.6\lib\site-packages\pandas\core\indexes\base.py", line 1640, in __contains__ 
    hash(key) 
    File "C:\Python3.6\lib\site-packages\pandas\core\indexes\base.py", line 1667, in __hash__ 
    raise TypeError("unhashable type: %r" % type(self).__name__) 
TypeError: unhashable type: 'Int64Index' 

我猜這事做與變量類型不匹配,但我看了,不能找到如何解決這個問題。

回答

1

我想你需要iloc

summer17.iloc[result_rows,2] += 1 

樣品:

summer17 = pd.DataFrame({'a':[1,2,3], 
         'b':[3,4,5], 
         'c':[5,9,7]}) 
#if reselt_rows is scalar 
result_rows = 1 

print(summer17) 
    a b c 
0 1 3 5 
1 2 4 9 
2 3 5 7 

summer17.iloc[result_rows,2] += 1 
print(summer17) 
    a b c 
0 1 3 5 
1 2 4 10 
2 3 5 7 

是一樣的:

#get value 
keg_count=summer17.iloc[result_rows,2] 
#increment 
keg_count +=1 
#set value 
summer17.iloc[result_rows,2] = keg_count 
print(summer17) 
    a b c 
0 1 3 5 
1 2 4 10 
2 3 5 7 

但如果result_rowslist1d array

result_rows = [1,2] 

#get all values per positions defined in result_rows 
#filter only first value by values[0] 
keg_count=summer17.iloc[result_rows,2].values[0] 
#increment 
keg_count +=1 
#set all values of result_rows by incremented value 
summer17.iloc[result_rows,2] = keg_count 
print(summer17) 
    a b c 
0 1 3 5 
1 2 4 10 
2 3 5 10 
+1

這比我想要做的要簡單得多。 – jon