Python-是否使用本地封闭来处理列表中的异常,理解复制库功能或其他不良Python实践?
我有一个功能,可以采用索引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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信您正在寻找的是
apply_map()
或apply()
dataframes的方法。apply()
的文档可以找到在这里,可以找到apply_map()
的文档在这里。如果要在数据框的所有元素中应用一个函数,则应使用apply_map()
。如果您只想在轴上应用功能,请使用apply()
。请记住,这些方法无法执行。I believe what you are looking for is either the
apply_map()
orapply()
method of dataframes. Documentation forapply()
can be found here, while documentation forapply_map()
can be found here. If you want to apply a function across all elements of a dataframe, you should useapply_map()
. If you want to only apply a function across an axis, useapply()
. Keep in mind that these methods cannot be performed in place.