Passing Operators As Functions To Use With Pandas Data Frames
I am selecting data from series on basis of threshold . >>> s = pd.Series(np.random.randn(5)) >>> s 0 -0.308855 1 -0.031073 2 0.872700 3 -0.547615 4
Solution 1:
I'm all about @cᴏʟᴅsᴘᴇᴇᴅ's answer and @Zero's linked Q&A...
But here is an alternative with numexpr
importnumexprasnes[ne.evaluate('s {} {}'.format(ops[cfg['op']], cfg['threshold']))]
0-0.3088551-0.0310733-0.547615Name: A, dtype: float64
I reopened this question after having been closed as a dup of How to pass an operator to a python function?
The question and answers are great and I showed my appreciation with up votes.
Asking in the context of a pandas.Series
opens it up to using answers that include numpy
and numexpr
. Whereas trying to answer the dup target with this answer would be pure nonsense.
Solution 2:
Define a dictionary of methods that can stand in for your operators.
importoperator
d = {
'more' : operator.gt,
'less' : operator.lt,
'equal' : operator.eq,
'not equal' : operator.ne
}
Now, just index into your dictionary and apply your function parameters.
m = d[cfg['op']](s, cfg['threshold'])
m
0False1True2True3False4False
dtype: bool
s[m]
1 -0.2620542 -1.300810
dtype: float64
Here,
d[cfg['op']](s, cfg['threshold'])
Is translated into
operator.lt(s, 0)
Post a Comment for "Passing Operators As Functions To Use With Pandas Data Frames"