Python-是否使用本地封闭来处理列表中的异常,理解复制库功能或其他不良Python实践?

发布于 2025-01-26 21:05:16 字数 817 浏览 1 评论 0原文

我有一个功能,可以采用索引pandas.series的事物和我想按组上使用这些事物的东西的数据框架。数据帧通常包含没有匹配的东西的组,因此简单的列表理解通常会引发异常。

我的蟒蛇很生锈。像这样的代码是否被认为是正常的?令我惊讶的是,它可能正在复制我应该使用的一些库功能。或者只是与其他方式相比,这可能是不良的做法。我对本地函数的理由是,除了成为列表理解的辅助功能之外,它没有用,那么为什么要将其整体化?

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 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. 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.

My Python is pretty rusty. Is code like this considered normal? It strikes me that it might be replicating some library function that I should use instead. 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?

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

说好的呢 2025-02-02 21:05:16

我相信您正在寻找的是apply_map()apply() dataframes的方法。 apply()的文档可以找到在这里,可以找到apply_map()的文档在这里。如果要在数据框的所有元素中应用一个函数,则应使用apply_map()。如果您只想在轴上应用功能,请使用apply()。请记住,这些方法无法执行。

I believe what you are looking for is either the apply_map() or apply() method of dataframes. Documentation for apply() can be found here, while documentation for apply_map() can be found here. If you want to apply a function across all elements of a dataframe, you should use apply_map(). If you want to only apply a function across an axis, use apply(). Keep in mind that these methods cannot be performed in place.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文