I should get certain data from user and sometimes I don’t. This is when it breaks the code:
code:
def check_user_data(meta_df = pd.DataFrame(),
params = ['param1','param2']):
if meta_df['alpha'] in params:
print('Alpha is available')
if meta_df['beta'] in params:
print('Beta is available')
user_df = pd.Series(index=['alpha'],data=['alpha1'])
check_user_data(meta_df = user_df,
params = ['alpha1','beta1'])
Present output:
Alpha is available
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
KeyError: 'beta'
The above exception was the direct cause of the following exception:
KeyError Traceback (most recent call last)
Cell In[47], line 5, in check_user_data(meta_df, params)
----> 5 if meta_df['beta'] in params:
6 print('Beta is available')
KeyError: 'beta'
>Solution :
To avoid the error, you should first check if the beta exists in the df and then look for it being in params, this way, if the df does not contain that column then the code goes on without a problem
def check_user_data(meta_df=pd.DataFrame(), params=['param1', 'param2']):
if 'alpha' in meta_df and meta_df['alpha'] in params:
print('Alpha is available')
if 'beta' in meta_df and meta_df['beta'] in params:
print('Beta is available')
user_df = pd.Series(index=['alpha'], data=['alpha1'])
check_user_data(meta_df=user_df, params=['alpha1', 'beta1'])