简体   繁体   English

将运算符作为函数传递给Pandas数据框

[英]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    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

I want to use ops[cfg['op']] in last line of code , instead of '<'. 我想在代码的最后一行中使用ops [cfg ['op']],而不要使用'<'。 I am willing to change key , values of ops dict if required (like -lt instead of <). 如果愿意,我愿意更改key,ops dict的值(例如-lt代替<)。 How this can be done? 如何做到这一点?

I'm all about @cᴏʟᴅsᴘᴇᴇᴅ's answer and @Zero's linked Q&A... 我全都关心@cᴏʟᴅsᴘᴇᴇᴅ的答案和@Zero的相关问答。
But here is an alternative with numexpr 但是这是numexpr的替代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

I reopened this question after having been closed as a dup of How to pass an operator to a python function? 在作为如何将运算符传递给python函数的dup封闭后,我重新打开了这个问题

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 . pandas.Series上下文中pandas.Series可以使用包括numpynumexpr答案进行numexpr Whereas trying to answer the dup target with this answer would be pure nonsense. 而试图用这个答案来回答重复目标将是纯粹的废话。

Define a dictionary of methods that can stand in for your operators. 定义可以代表您的操作员的方法的词典。

import operator    
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

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

s[m]

1   -0.262054
2   -1.300810
dtype: float64

Here, 这里,

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

Is translated into 被翻译成

operator.lt(s, 0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM