传递条件表达式作为函数参数

时间:2015-12-08 09:25:08

标签: python pandas

我正在为在不规则网格上生长的区域编写函数:在种子仓中开始,找到相邻的仓,并在满足某个要求时将它们包含在返回的仓索引集中。我希望这个要求是任意的,例如'> 2','> = 2','== 2'等等。所以语法是:

myregion = get_region(bin_coordinates, bin_values, seed_bin, '> 2')

将返回其值大于2的相邻区域的区域。

基本上我正在寻找与pandas库相同的功能,在查询HDF存储时可以使用以下内容:

store.select('dfq',where="A>0 or C>0")

我当然可以用if / else语句编写某种解析器来翻译'> 2'进入代码,但我想知道是否有更优雅的方式?

1 个答案:

答案 0 :(得分:1)

使用lambda(匿名函数),例如lambda x:x> 2。将getregion声明为例如getregion(coordinates,values,testfun),并通过例如getregion(thesecoords,thesevalues,lambda x:x> 2),然后在getregion中使用例如如果testfun(值)。但是,选择比testfun更好的名称,描述True的结果意味着什么。

另一种方法是定义一些标准'评估函数并将其名称传递给getregion,例如

def gt2(x):
    return (x>2)

为lambda示例声明getregion:

def getregion( coordinates, values, testfun ):
    ...
    if testfun(x):
        ...

并像这样调用getregion:

getregion(thesecoordinates, thesevalues, gt2 )

HTH 巴尼

相关问题