Python 将运算符作为函数传递以用于数据帧

Python 将运算符作为函数传递以用于数据帧,python,pandas,conditional,series,dynamic-execution,Python,Pandas,Conditional,Series,Dynamic Execution,我根据阈值从系列中选择数据 >>> s = pd.Series(np.random.randn(5)) >>> s 0 -0.308855 1 -0.031073 2 0.872700 3 -0.547615 4 0.633501 dtype: float64 >>> cfg = {'threshold' : 0 , 'op' : 'less' } >>> ops = {'less' : '<'

我根据阈值从系列中选择数据

>>> s = pd.Series(np.random.randn(5))
>>> s
0   -0.308855
1   -0.031073
2    0.872700
3   -0.547615
4    0.633501
dtype: float64
>>> cfg = {'threshold' : 0 , 'op' : 'less' }
>>> ops = {'less' : '<', 'more': '>' , 'equal': '==' , 'not equal' : '!='}
>>> ops[cfg['op']]
'<'
>>> s[s < cfg['threshold']]
0   -0.308855
1   -0.031073
3   -0.547615
dtype: float64
>s=pd.系列(np.random.randn(5))
>>>
0   -0.308855
1   -0.031073
2    0.872700
3   -0.547615
4    0.633501
数据类型:64
>>>cfg={'threshold':0,'op':'less'}
>>>ops={'less':'','equal':'='','notequal':'!='}
>>>操作[cfg['op']]

“定义一个方法字典,可以代替运算符

import operator    
d = {
         'more'  : operator.gt,
         'less'  : operator.lt,
         'equal' : operator.eq, 
         'not equal' : operator.ne
   }
现在,只需索引到字典中并应用函数参数

m = d[cfg['op']](s, cfg['threshold'])
m

0    False
1     True
2     True
3    False
4    False
dtype: bool

s[m]

1   -0.262054
2   -1.300810
dtype: float64
这里,

d[cfg['op']](s, cfg['threshold']) 
翻译成

operator.lt(s, 0)

我只关心@cᴏʟᴅsᴘᴇᴇᴅ's答案和@Zero的链接问答…
但是这里有一个使用
numexpr

import numexpr as ne

s[ne.evaluate('s {} {}'.format(ops[cfg['op']], cfg['threshold']))]

0   -0.308855
1   -0.031073
3   -0.547615
Name: A, dtype: float64

在作为一个傻瓜被关闭后,我重新开始了这个问题

问题和答案都很好,我用最多的选票表达了我的感激之情


pandas.Series
的上下文中提问可以使用包括
numpy
numexpr
的答案。然而,试图用这个答案回答dup目标完全是胡说八道。

使用
操作符.xx
-
gt
lt
eq
ne
看哇,这太棒了!你可能已经得到了公认的答案。。。但我先吃了大约一秒钟(:又回来了。显然OP喜欢这两个答案,无法做出决定。@piRSquared不久前,我感谢你们对我的银牌的支持,现在是时候为我的金牌做同样的事情了。如果没有帮助、支持和投票,我不可能做到这一点。所以,谢谢你们。:)不是我干的…是你干的!恭喜!同样。