1
當我嘗試執行下面的代碼時,我得到一個KeyError: ('user rating score', 'occurred at index title')
回溯。我嘗試在apply()
函數中的remove_na_scores
之後更改軸,但是沒有任何工作。使用數據幀的KeyError異常
import pandas as pd
import pprint
shows = pd.read_csv('/Users/WilliamStevens/Downloads/netflix_shows.csv')
pprint.pprint(shows.head())
shows.info()
shows_df = shows.groupby(['ratingDescription']).mean()
print(shows_df)
missing_user_scores = shows[shows['user rating score'].isnull()]
mean_scores = shows.groupby(['ratingDescription'])['user rating score'].mean()
def remove_na_scores(row):
if pd.isnull(row['user rating score']):
return mean_scores[row['rating']]
else:
return row['user rating score']
shows['user rating score'] = shows.apply(remove_na_scores)
print(shows['user rating score'])
完整回溯是如下:
Traceback (most recent call last):
File "netflix.py", line 28, in <module>
shows['user rating score'] = shows.apply(remove_na_scores)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pandas/core/frame.py", line 4163, in apply
return self._apply_standard(f, axis, reduce=reduce)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pandas/core/frame.py", line 4259, in _apply_standard
results[i] = func(v)
File "netflix.py", line 23, in remove_na_scores
if pd.isnull(row['user rating score']):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pandas/core/series.py", line 601, in __getitem__
result = self.index.get_value(self, key)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pandas/indexes/base.py", line 2169, in get_value
tz=getattr(series.dtype, 'tz', None))
File "pandas/index.pyx", line 105, in pandas.index.IndexEngine.get_value (pandas/index.c:3567)
File "pandas/index.pyx", line 113, in pandas.index.IndexEngine.get_value (pandas/index.c:3250)
File "pandas/index.pyx", line 163, in pandas.index.IndexEngine.get_loc (pandas/index.c:4373)
KeyError: ('user rating score', 'occurred at index title')
請顯示整個回溯,這樣我們知道發生錯誤的位置。 –
回溯(最近最後調用): 文件 「netflix.py」,第28行,在 顯示[ '用戶等級分數'] = shows.apply(remove_na_scores) 文件「/Library/Frameworks/Python.framework/版本/ 3.5/lib/python3.5/site-packages/pandas/core/frame.py「,行4163,in apply return self._apply_standard(f,axis,reduce = reduce) 文件」/ Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pandas/core/frame.py「,第4259行,在_apply_standard中 results [i] = func(v) 文件」netflix.py「,第23行,在remove_na_scores if pd.isnull(row ['user rating score']): –
bullybear17
File「/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pandas/core /series.py「,第601行,在__getitem__ result = self.index.get_value(self,key) File」/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/ pandas/indexes/base.py「,第2169行,在get_value tz = getattr(series.dtype,'tz',None)) pandas.index.IndexEngine中的文件」pandas/index.pyx「,第105行。 get_value(pandas/index.c:3567) – bullybear17