pandas python dataframe检查不存在的列或行

y53ybaqx  于 2023-08-01  发布在  Python
关注(0)|答案(2)|浏览(168)

我应该从用户那里得到某些数据,有时我没有。这就是它打破代码的时候:
代码:

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'])

字符串
当前输出:

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'

tv6aics1

tv6aics11#

为了避免错误,您应该首先检查df中是否存在beta,然后在params中查找它,这样,如果df中不包含该列,代码就不会出现问题

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'])

字符串

xienkqul

xienkqul2#

除了首先检查值之外,你还可以使用try/accept块来代替:

try:
        if meta_df['alpha'] in params:
            print('Alpha is available')
    except KeyError:
        # Do something when value is unavailable
        pass

    try:
        if meta_df['beta'] in params:
            print('Beta is available')
    except KeyError:
        # Do something when value is unavailable
        pass

字符串

相关问题