#python #keyerror #getlocation
Вопрос:
Я получил ошибку, как показано ниже:
Вышеупомянутое исключение было прямой причиной следующего исключения:
Traceback (most recent call last): File "C:UsersstevePycharmProjectsEmpirical Asset via Machine Learningvenvlibsite-packagespandascoreindexesbase.py", line 3361, in get_loc return self._engine.get_loc(casted_key) File "pandas_libsindex.pyx", line 76, in pandas._libs.index.IndexEngine.get_loc File "pandas_libsindex.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc File "pandas_libshashtable_class_helper.pxi", line 5198, in pandas._libs.hashtable.PyObjectHashTable.get_item File "pandas_libshashtable_class_helper.pxi", line 5206, in pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: 'aggbeta_lxrd' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:UsersstevePycharmProjectsEmpirical Asset via Machine Learningmain.py", line 98, in lt;modulegt; exp_df.insert(exp_df.columns.get_loc(char) 1, f"{char}_missing", np.nan) File "C:UsersstevePycharmProjectsEmpirical Asset via Machine Learningvenvlibsite-packagespandascoreindexesbase.py", line 3363, in get_loc raise KeyError(key) from err KeyError: 'aggbeta_lxrd'
Вот мой код:
firm_char_ = np.sort(np.append(firm_char, np.asarray(['q_tot', 'aggbeta_lxrd']))) exp_df = exp_df.sort_values(by=['date']) # Rank firm characteristics within period cross-secionally and normalize to [-1, 1] def char_rank(group): group[firm_char_] = group[firm_char_].rank(pct=True) * 2 - 1 return group for char in firm_char_: exp_df.insert(exp_df.columns.get_loc(char) 1, f"{char}_missing", np.nan) char_missing = np.array([f"{char}_missing" for char in firm_char_]) # Fill by cross-secion median by period def fill_missing(group): group[char_missing] = group[firm_char_].isnull().astype(np.int64) group[firm_char_] = group[firm_char_].fillna(group[firm_char_].median()) return group
Я не знаю, как это исправить, я надеюсь, что кто-нибудь сможет мне помочь. Спасибо.