我应该从用户那里得到某些数据,有时我没有。这就是它打破代码的时候:
代码:
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'
型
2条答案
按热度按时间tv6aics11#
为了避免错误,您应该首先检查df中是否存在beta,然后在params中查找它,这样,如果df中不包含该列,代码就不会出现问题
字符串
xienkqul2#
除了首先检查值之外,你还可以使用try/accept块来代替:
字符串