简体   繁体   English

在 python 函数中使用 2 个异常

[英]Use 2 exceptions in a python function

I want to write a function to calculate the mode of a column in a grouped by dataframe.我想编写一个函数来计算按数据帧分组的列的模式。 If the values of a group has not a mode, the first exception: calculate the median and if the values of the group are all null values, the second exception:do nothing.如果组的值没有众数,第一个例外:计算中位数,如果组的值都是空值,第二个例外:什么都不做。 The sample dataframe is like below:示例数据框如下所示:

dataframe = pd.DataFrame({'b':['b1','b1','b1','b1','b1','b1','b2','b2','b2','b2','b2','b2','b3','b3','b3'],'d':[0.1,None,0.12,None,None,0.13,1,2,1,1,None,None,None,None,None]})

The function is as follow:功能如下:

def fill_mode(group):
    try:
        group['mode'] = mode(group['d'])
    except:
        not_nulls = group[~group['d'].isnull()]
        group['mode'] = median(not_nulls['d'])
    except:
        pass
    return group 

And the apply function is as bellow:应用函数如下:

dataframe = dataframe.groupby('b').apply(fill_mode)

Which raises this error :这引发了这个错误:

SyntaxError: default 'except:' must be last语法错误:默认 'except:' 必须是最后一个

The final output should be like this:最终的输出应该是这样的:

在此处输入图片说明

You need a second try/except block.您需要第二个try/except块。

def fill_mode(group):
    try:
        group['mode'] = mode(group['d'])
    except:
        try:
            not_nulls = group[~group['d'].isnull()]
            group['mode'] = median(not_nulls['d'])
        except:
            pass
    return group 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM