装饰器统计函数执行次数

当用apply处理大文件时,无法知道程序处理了多少行,可以用装饰器统计函数执行次数。

注意这里的apply()函数在pandas版本0.20.3中好用,其它不清楚,在这个版本中,当返回的list长度与dataframe的列数相同时,可直接赋给对应的列,当不同时,会生成一个series。

有的版本的pandas无论列数与list长度是否相等,均生成series,神坑!!!!!

如下num不能是变量,square_call_count返回值必须是它自己

def decorate_square(function):
    num = [0]
    def square_call_count(row):
        num[0]  += 1
        # print(row)
        print('square函数执行次数为:', num[0])
        return function(row)
    return square_call_count

@decorate_square
def square(row):
    r = map(lambda x: x * x, row)
    return list(r)

a = pd.DataFrame({
                    'a': [2] * 5 ,
                    'b': [3] * 5 ,
                    'c': [4] * 5
                 })
print(a)
a = a.apply( square, axis=1)
print(a)
#    a  b  c
# 0  2  3  4
# 1  2  3  4
# 2  2  3  4
# 3  2  3  4
# 4  2  3  4
# square函数执行次数为: 1
# square函数执行次数为: 2
# square函数执行次数为: 3
# square函数执行次数为: 4
# square函数执行次数为: 5
# square函数执行次数为: 6
#    a  b   c
# 0  4  9  16
# 1  4  9  16
# 2  4  9  16
# 3  4  9  16
# 4  4  9  16

参考:https://blog.csdn.net/qq_31603575/article/details/80011287

https://www.runoob.com/w3cnote/python-func-decorators.html

https://www.cnblogs.com/cicaday/p/python-decorator.html

posted on 2019-05-24 13:12  吃我一枪  阅读(527)  评论(0编辑  收藏  举报

导航