• 装饰器统计函数执行次数


    当用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

  • 相关阅读:
    gradient函数
    matlab函数
    二进制中1的个数
    豆瓣电影数据分析
    豆瓣电影Top250数据爬取学习
    numpy_将nan替换为均值
    多次条形图
    Gym
    Educational Codeforces Round 59 (Rated for Div. 2)
    Codeforces Round #535 (Div. 3)
  • 原文地址:https://www.cnblogs.com/xxswkl/p/10917578.html
Copyright © 2020-2023  润新知