将运算符作为函数传递给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
我想在代码的最后一行中使用ops [cfg ['op']]而不是'<'.我愿意根据需要更改key,ops dict的值(例如-lt而不是<).如何做到这一点?
I want to use ops[cfg['op']] in last line of code , instead of '<'. I am willing to change key , values of ops dict if required (like -lt instead of <). How this can be done?
推荐答案
我只关心@cᴏʟᴅsᴘᴇᴇᴅ的答案和@Zero的链接的问答集...
但这是numexpr
I'm all about @cᴏʟᴅsᴘᴇᴇᴅ's answer and @Zero's linked Q&A...
But here is an alternative with 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
在作为的dup封闭后,我重新打开了这个问题.如何将运算符传递给python函数?
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.
在pandas.Series
的上下文中提问可以使用包含numpy
和numexpr
的答案来打开它.而试图用这个答案来回答dup目标将完全是胡说八道.
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.
这篇关于将运算符作为函数传递给Pandas数据框使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!