Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python dataframe check a non-existing column or row

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading