简体   繁体   English

Python - 是否使用本地闭包来处理列表理解中的异常,从而复制库 function 或其他不好的 Python 做法?

[英]Python - Is using a local closure to handle exceptions in a list comprehension duplicating a library function or otherwise bad Python practice?

I have a function that takes an indexed pandas.Series of things and a dataframe of stuff that I want to use the things on group by group.我有一个 function,它采用索引pandas.Series的东西和一个 dataframe 的东西,我想逐组使用这些东西。 It is common for the dataframe to contain groups for which there is no matching thing, so a simple list comprehension will often throw exceptions. dataframe 包含没有匹配项的组是很常见的,因此简单的列表理解通常会抛出异常。

My Python is pretty rusty.我的 Python 已经生锈了。 Is code like this considered normal?这样的代码被认为是正常的吗? It strikes me that it might be replicating some library function that I should use instead.令我震惊的是,它可能正在复制一些我应该使用的库 function。 Or just that it might be bad practice compared to some other way.或者只是与其他方式相比,这可能是不好的做法。 My justification for the local function is that it has no use aside from being a helper function for the list comprehension, so why make it global?我对本地 function 的理由是,除了作为列表理解的助手 function 之外,它没有任何用处,那么为什么要把它设为全局呢?

def use_things(things, stuff_to_use_things_on):
    stuff_grouped = stuff_to_use_things_on.groupby(things.index.names)

    # find and use the right thing, or else move on
    # local closure since this function has no real use outside this context
    def use_thing(name, group):
        try:
            return things.loc[(name)].do_something(group)
        except:
            return None

    # stuff might contain groups that there is no thing for
    results = [use_thing(name, group) for (name, group) in stuff_grouped]
    
    return pd.concat(results)

I believe what you are looking for is either the apply_map() or apply() method of dataframes.我相信您正在寻找的是数据帧的apply_map()apply()方法。 Documentation for apply() can be found here , while documentation for apply_map() can be found here . apply()的文档可在此处找到,而apply_map()的文档可在此处找到。 If you want to apply a function across all elements of a dataframe, you should use apply_map() .如果你想在 dataframe 的所有元素上应用 function,你应该使用apply_map() If you want to only apply a function across an axis, use apply() .如果您只想跨轴应用 function,请使用apply() Keep in mind that these methods cannot be performed in place.请记住,这些方法不能就地执行。

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

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