0

I'm writing a function for region growing on an irregular grid: Start in a seed bin, find the neighboring bins, and include them in the set of returned bin indices if a certain requirement is fulfilled. I would like for the requirement to be arbitrary, e.g., '> 2', '>= 2', '== 2', etc.. So the syntax would be:

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

and the region of neighboring bins, whose values are greater than 2 will be returned.

Essentially I'm looking for the same functionality as in the pandas library, where the following is possible when querying a HDF store:

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

I could of course write some sort of parser with if/else statements to translate '> 2' into code, but I was wondering if there is a more elegant way?

1
  • 1
    pass in a lambda (an anonymous function), e.g. lambda x: x>2. Declare getregion as e.g. getregion(coordinates,values,testfun), and call it by e.g. getregion(thesecoords,thesevalues,lambda x: x>2), then in getregion use the test by e.g. if testfun(value). Choose a better name than testfun, though, one that describes what a result of True means. Commented Dec 8, 2015 at 9:28

1 Answer 1

1

Use a lambda (an anonymous function), e.g. lambda x: x>2. Declare getregion as e.g. getregion(coordinates,values,testfun), and call it by e.g. getregion(thesecoords,thesevalues,lambda x: x>2), then in getregion use the test by e.g. if testfun(value). Choose a better name than testfun, though, one that describes what a result of True means.

Another approach would be to define some 'standard' evaluation functions and pass their name to getregion, e.g.

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

declare getregion as for lambda example:

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

and call getregion like this:

getregion(thesecoordinates, thesevalues, gt2 )

HTH Barny

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, that's a good solution. Still wonder wonder how the pandas functionality is implemented though...
They have implemented a conditional expression evaluator - in the pandas source search for 'where=' in pytables.py. I guess the detailed implementation is in there somewhere...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.