我得到如下错误:
上述异常是以下异常的直接原因:
Traceback (most recent call last):
File "C:\Users\steve\PycharmProjects\Empirical Asset via Machine Learning\venv\lib\site-packages\pandas\core\indexes\base.py", line 3361, in get_loc
return self._engine.get_loc(casted_key)
File "pandas\_libs\index.pyx", line 76, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 5198, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_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:\Users\steve\PycharmProjects\Empirical Asset via Machine Learning\main.py", line 98, in <module>
exp_df.insert(exp_df.columns.get_loc(char) + 1, f"{char}_missing", np.nan)
File "C:\Users\steve\PycharmProjects\Empirical Asset via Machine Learning\venv\lib\site-packages\pandas\core\indexes\base.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
我不知道如何解决它,我希望任何人都可以帮助我。谢谢。